Help with singly linked list in c++

class Node
{
public:
int data;
Node * next;
};
Node *p1, *p2, *p3;
Assume also that the following statements have been executed:
p1 = new(nothrow) Node;
p2 = new(nothrow) Node;
p3 = new(nothrow) Node;


Tell what will be displayed by each of the following code segments or explain why an error occurs.

Question # 1
p1 -> data = 123;
p2 -> data = 456;
p1 -> next= p2;
p2 -> next= 0;
cout << p1 -> data << " " << p1 ->next->data << endl;

Question #2
p1 ->data = 12;
p2 -> data = 34;
p1 = p2;
cout << p1 -> data << " " << p2->data << endl;

Question #3
p1 ->data = 12;
p2 -> data = 34;
*p1 = *p2;
cout << p1 -> data << " " << p2->data << endl;

Question # 4
p1 -> data = 123;
p2 -> data = 456;
p1 -> next= p2;
p2 -> next= 0;
cout << p2 -> data << " " << p2 ->next->data << endl;

Question #5
p1 ->data = 12;
p2 -> data = 34;
p3 ->data = 34;
p1 ->next = p2;
p2 -> next = p3;
p3 -> next = 0;
cout << p1 -> data << " " << p1->next->data << endl;
cout << p2 -> data << " " << p2->next->data << endl;
cout << p1 -> next ->next->data <<endl;
cout << p3 ->data << endl;

I have attempted all of these and am not sure if I am right, my main issue is with the p1 = p2 in question 2, and the cout parts
closed account (o1vk4iN6)
The point of a linked list is that the "Node" contains the pointer to another Node, so you don't keep all the references to all the nodes.

1
2
3
4
5
6
7
8
9
struct Node {
     int data;
     Node* link;

     Node(int _data, Node* _link) : data(_data), link(_link) 
     { }
};

Node* root = new Node(0, new Node(1, new Node(3, nullptr) ) );
Topic archived. No new replies allowed.