Insertion in singly linked list at the end

In order to insert a node at the last, there are two following scenarios which need to be mentioned.

The node is being added to an empty list

The node is being added to the end of the linked list

in the first case,

The condition (head == NULL) gets satisfied. Hence, we just need to allocate the space for the node by using malloc statement in C. Data and the link part of the node are set up by using the following statements.

Since, ptr is the only node that will be inserted in the list hence, we need to make this node pointed by the head pointer of the list. This will be done by using the following Statements.

In the second case,

The condition Head = NULL would fail, since Head is not null. Now, we need to declare a temporary pointer temp in order to traverse through the list. temp is made to point the first node of the list.

Then, traverse through the entire linked list using the statements:

At the end of the loop, the temp will be pointing to the last node of the list. Now, allocate the space for the new node, and assign the item to its data part. Since, the new node is going to be the last node of the list hence, the next part of this node needs to be pointing to the null. We need to make the next part of the temp node (which is currently the last node of the list) point to the new node (ptr) .

Algorithm

Step 1: IF PTR = NULL

Write OVERFLOW
Go to Step 1
[END OF IF]

Step 2: SET NEW_NODE = PTR

Step 3: SET PTR = PTR - > NEXT

Step 4: SET NEW_NODE - > DATA = VAL

Step 5: SET NEW_NODE - > NEXT = NULL

Step 6: SET PTR = HEAD

Step 7: Repeat Step 8 while PTR - > NEXT != NULL

Step 8: SET PTR = PTR - > NEXT

[END OF LOOP]

Step 9: SET PTR - > NEXT = NEW_NODE

Step 10: EXIT

C Function

Output

Enter the item which you want to insert?
12
Node inserted
Press 0 to insert more ?
0
Enter the item which you want to insert?
23
Node inserted
Press 0 to insert more ?
2