Inserting a new element into a singly linked list at the end is quite simple.
There are the
following steps that need to be followed in order to insert a new node in the list at the end.
1. Allocate the space for the new node and store data into the data part of the node and store
NULL at the address part of the node.
ptr = (struct node *) malloc(sizeof(struct node *));
ptr → data = item
ptr->next=NULL
2. We need to declare a temporary pointer temp in order to traverse through the list. temp is
made to point to the first node of the list.
temp = ptr
2. Then, traverse through the entire linked list
while (temp→ next != NULL)
temp = temp → next;
3. At the end of the loop, the temp will be pointing to the last node of the list. 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) .
temp = ptr;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = 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