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 5.17). This next pointer will be used for connecting with other nodes (as we will see shortly):

Figure 5.17

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

Figure 5.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 5.19

To connect the first node with newNode, the next pointer of temp1 will be set to point at newNode (see Figure 5.20 (a)). After connecting with newNode, the temp1 pointer will be moved further and set to point at newNode (see Figure 5.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 5.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 5.21

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