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.
ptr = (struct node *) malloc(sizeof(struct node *));
ptr → data = item
ptr->next=NULL
2. Make the linked part of the new node point to the existing first node of the list.
ptr->next = head;
3. At the last, we need to make the new node the first node of the list.
head = ptr;
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 PTR as a new node
Step 3: SET PTR → DATA = VAL
Step 4: SET PTR → NEXT = HEAD
Step 5: SET HEAD= PTR
Step 6: EXIT
The time complexity to insert a node at the beginning of the given linked list is: O(1)