Adding elements at the end of the list

If you have mastered the traversing the link list in the last section, you will find it very useful in this section. Let us look at the code in the section below. You can download the source code here.

To add an element to the end of a list we need to traverse it, starting from the first node going right up to the node whose "next" pointer points to NULL. This is because, the last node's "next" pointer will always be NULL. Once we reach this node we just have to make the "next" pointer point to our new node. Our new node now becomes the last node.

Let us look at the function addToEnd. We start of by assigning a temporary variable "temp" to the first node. Once this is done we traverse the list till the end this is done using the while loop. At the end of the loop temp will be pointing to the last node. All we have to do is use the "next" field of the node to which temp is pointing to and assign it to the address of the new node. The figure below shows the same in a pictorial form

Pictorial form of above operation
Pictorial form of above operation
Pictorial form of above operation

Try Solving this...

In the last section I gave a problem to add a name and a number to the begining of a list. Now add a function to add the same at the end of the list. The solution is avaliable here