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)
- Insert a whole linked list into other at k-th position
- Insertion at Specific Position in a Circular Doubly Linked List
- Insert N elements in a Linked List one after other at middle position
- Insert node into the middle of the linked list
- Delete a Linked List node at a given position
- Delete a Doubly Linked List node at a given position
- Create a linked list from two linked lists by choosing max element at each 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
- Sorted insert for circular linked list
- Swap Kth node from beginning with Kth node from end in a Linked List
- Make a loop at k-th position in a linked list
- Sorted insert in a doubly linked list with head and tail pointers
- Remove Nth node from end of the Linked List
- Program for n'th node from the end of a Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.