Creating a singly linked list

We will start by creating a new node by the name of newNode. When prompted, we will enter the value for its data member and then set the next newNode pointer to NULL ( as shown in Figure 4.17). This next pointer will be used for connecting with other nodes (as we will see shortly):

Figure 4.17

After the first node is created, we will make the following two pointers point at it as follows:

  • startList: To traverse the singly linked list, we will need a pointer that points at the first node of the list. So, we will define a pointer called startList and set it to point at the first node of the list.
  • temp1: In order to connect with the next node, we will need one more pointer. We will call this pointer temp1, and set it to point at the newNode (see Figure 4.18):

Figure 4.18

We will now create another node for the linked list and call that newNode as well. The pointer can point to only one structure at a time. So, the moment we create a new node, the newNode pointer that was pointing at the first node will now point at the recently created node. We will be prompted to enter a value for the data member of the new node, and its next pointer will be set to NULL.

You can see in the following diagram that the two pointers, startList and temp1, are pointing at the first node and the newNode pointer is pointing at the newly created node. As stated earlier, startList will be used for traversing the linked list and temp1 will be used for connecting with the newly created node as follows:

Figure 4.19

To connect the first node with newNode, the next pointer of temp1 will be set to point at newNode (see Figure 4.20 (a)). After connecting with newNode, the temp1 pointer will be moved further and set to point at newNode (see Figure 4.20 (b)) so that it can be used again for connecting with any new nodes that may be added to the linked list in future:

Figure 4.20

Steps three and four will be repeated for the rest of the nodes of the linked list. Finally, the singly linked list will be ready and will look something like this:

Figure 4.21

Now that we have created the singly linked list, the next step is to sort the linked list in ascending order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset