Algorithm to Insert a Node at the Front of the Linked List

Insertion in the singly linked list at the beginning

Inserting a new element into a singly linked list at the beginning is quite simple. We just need to make a few adjustments in the node links. There are the following steps that need to be followed in order to insert a new node in the list at the beginning.

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. Make the linked part of the new node point to the existing first node of the list.

newnode->next = head;  

3. At the last, we need to make the new node the first node of the list.

head = newnode;  


Algorithm to insert a new node at the end

Step 1: IF HEAD = NULL

Write OVERFLOW

     Go to Step 6

    [END OF IF]

Step 2: SET NEWNODE as a new node

Step 3: SET  NEWNODE → DATA = VAL

Step 4: SET NEWNODE → NEXT = HEAD

Step 5: SET HEAD= NEWNODE

Step 6: EXIT

 

The time complexity to insert a node at the beginning of the given linked list is: O(1)