Linked list with only one pointer?

Jun 1, 2016 at 2:34am
Given
1
2
3
4
5
struct Node{
    int data;
    Node *next;
};
Node *head;

how do I allocate three nodes where head points to the first node? I am not allowed to declare another variable.
Jun 1, 2016 at 2:56am
head = new Node;
head->next=new Node;
head->next->next=new Node;
Jun 1, 2016 at 3:18am
1
2
3
4
5
6
head = new Node;
head -> data = 1;
head -> next = new Node;
head-> next -> data = 2;
head -> next -> next = new Node;
head -> next -> next -> data = 3;

Thank you for responding. Would this be correct?
Jun 1, 2016 at 8:53am
You need to set the last notes next pointer to NULL
to mark that you are at the end of the linked list.

head -> next -> next -> next = NULL;

or in C++11

head -> next -> next -> next = nullptr;



Last edited on Jun 1, 2016 at 8:57am
Topic archived. No new replies allowed.