Inserting a Node
Procedure to insert a new node in the beginning, end or at a specific position in the linked list.
Insert at Beginning :
Insert at N-th Position :
Indexing for the linked list is considered to start from 1 in the above code where the index of the first node is 1.
If index is considered to start from 0, change condition to pos - 1 instead of pos - 2 in the for loop.
Insert at End in O(1) Time :
In the above function, an additional pointer named last is taken which will always point to the last node of the linked list. Through this, we can insert a new node to the end of list in constant time.
Insert at End in O(n) Time :
Contributed by Nitin Ranganath
Last updated