Skip to content
enengee
Go back

Understanding Pointers in C++: Part I

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:

Illustration:

Figure 1. How nodes are allocated in memory.
Figure 1. How nodes are allocated in memory.

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):

Analyzing the remaining command similarly, we have the following illustration:

Figure 2. How nodes link together to form a singly linked list.
Figure 2. How nodes link together to form a singly linked list.

Share this post on:

Previous Post
Understanding Pointers in C++: Part II
Next Post
Book Review: Test-Driven Java Development by Viktor Farcic and Alex Garcia (2015)