Insert a node at a specific position in a linked list
Given a singly linked list, a position and an element, the task is to write a program to insert that element in a linked list at a given position.
Input: 3->5->8->10, data = 2, position = 2
Input: 3->5->8->10, data = 11, position = 5
Approach: To insert a given data at a specified position, the below algorithm is to be followed:
- Traverse the Linked list upto position-1 nodes.
- Once all the position-1 nodes are traversed, allocate memory and the given data to the new node.
- Point the next pointer of the new node to the next of current node.
- Point the next pointer of current node to the new node.
Below is the implementation of the above algorithm.
Time Complexity: O(N)
Auxiliary Space: O(1)
My Personal Notes arrow_drop_up
Please Login to comment...