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 Output: 3->2->5->8->10 Input: 3->5->8->10, data = 11, position = 5 Output: 3->5->8->10->11
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.
Linked list before insertion: 3 5 8 10 Linked list after insertion of 12 at position 3: 3 5 12 8 10 Linked list after insertion of 1 at position 1: 1 3 5 12 8 10 Linked list after insertion of 15 at position 7: 1 3 5 12 8 10 15
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Insertion at Specific Position in a Circular Doubly Linked List
- Insert N elements in a Linked List one after other at middle position
- Insert a whole linked list into other at k-th position
- Insert a node in Linked List before a given node
- Insert node into the middle of the linked list
- Create a linked list from two linked lists by choosing max element at each position
- Delete a Linked List node at a given position
- Delete a Doubly Linked List node at a given position
- Create new linked list from two given linked list with greater element at each node
- Rotate the sub-list of a linked list from position M to N to the right by K places
- Insert a node after the n-th node from the end
- Given a linked list which is sorted, how will you insert in sorted way
- Sorted insert for circular linked list
- Insert value in sorted way in a sorted doubly linked list
- Sorted insert in a doubly linked list with head and tail pointers
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Make a loop at k-th position in a linked list
- Swap Kth node from beginning with Kth node from end in a Linked List
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.