Algorithm to Insert a Node at the End of the Linked list

Insertion at the end

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.  

newnode = (struct node *) malloc(sizeof(struct node *));  

newnode → data = item 

newnode->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 = head

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 = head;  

        while (temp -> next != NULL)  

        {  

            temp = temp -> next;  

        }  

        temp->next = newnode;  

       

Algorithm

Step 1: CREATE A NEW NODE

Step 2: IF START= NULL Write OVERFLOW

    Go to Step 1

   [END OF IF]

Step 3: SET NEW_NODE - > DATA = VAL

Step 4: SET NEW_NODE - > NEXT = NULL

Step 5: SET TEMP = HEAD

Step 6: Repeat Step 7 while TEMP - > NEXT != NULL

Step 7: SET TEMP = TEMP - > NEXT

[END OF LOOP]

Step 8: SET TEMP - > NEXT = NEW_NODE

Step 9: EXIT