Singly Linked List Insertion in Middle
The steps to insert a node in the middle of the list are as follows:
- Create new node
- Traverse the list, checking to find the node to insert the new node after.
- Set the new node's link to be a copy of the current node's link
- Change the current nodes link to point to the new node.
Insertion in the middle of a Singly Linked List is O(n) as the entire list may have to be traversed.
Example:
Insert ruler after book
- Create node ruler
- Traverse the List
- Is Head = book? -No
- Is paper = book? - No
- Is book = book? - Yes
- Set ruler.link = pen
- Set book.link = ruler
A new node, Ruler was added to the middle of the list after the node book, and this is the new layout for the Singly Linked List.