Linked list with only one pointer?

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.
head = new Node;
head->next=new Node;
head->next->next=new Node;
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?
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
Topic archived. No new replies allowed.