Use C++ class Node{ public: Node ( int = 0 ); // constructor with default value
ID: 3939995 • Letter: U
Question
Use C++
class Node{
public:
Node ( int = 0 ); // constructor with default value for
// info field
int info; // data
Node * next; // pointer to next node in the list
};
and put the constructor in Node.cpp
// Constructor
Node::Node ( int data )
{
info = data;
next = nullptr;
}
Write the following using the Node class.
A function that copies a linked list pointed to by ptr and returns a pointer to the copied list. Please note: the copied list should be independent of the original list; the original list can be destroyed and the copy should still remain.
const Node * copy (Node * ptr);
Explanation / Answer
Need to perform 'Deep copy' here :
const Node * copy (Node * ptr)
{
//Create new list to hold copied items
Node* newNode = new Node;
//Return if empty list
if (ptr->next == 0)
{
return newNode;
}
while(ptr !=NULL)
{
newNode->info = ptr->info;
newNode->next = ptr->next;
ptr = ptr ->next;
}
return newNode;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.