Before diving into the problem, let’s first define a “node” structure:
struct ListNode {
int value;
ListNode* next;
ListNode(int x): value(x), next(NULL) {}
};
With the above structure, we can create 3 nodes like this:
ListNode* head = new ListNode(1);
ListNode* node2 = new ListNode(2);
ListNode* node3 = new ListNode(3);
Let’s explain the meaning of the above assignment statements in more detail:
- The
new ListNode(1)operator allocates memory on the HEAP and returns the address of this memory region. ListNode* head: declares a pointer variable that points to theListNodedata type; this pointer variable is stored on the STACK.- The assignment
ListNode* head = new ListNode(1): assigns a memory address to a pointer. An assignment involving a pointer usually has a pointer on the left side and a memory address on the right side. Thus, the assignment can be understood as: the pointerheadpoints to the memory location at address , which storesListNode(1).
Illustration:
Next, link these 3 nodes together to create a singly linked list:
head->next = node2;
node2->next = node3;
The above assignments are explained in a completely similar way (you will notice that essentially, this operation is the same as the allocation above):
headis a pointer variable on the STACK that points to memory on the HEAP of typeListNodecontainingvalue=1andnext=NULL. Thus,head->nextis thenextpointer variable within thatListNodeon the HEAP.- The command
head->next = node2has a pointer on its left side and the address of the memory on the HEAP thatnode2is pointing to on its right side (value=2andnext=NULL). As analyzed above, this assignment makes thehead->nextpointer point to the memory location at the address ofnode2.
Analyzing the remaining command similarly, we have the following illustration: