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 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
- Swap Kth node from beginning with Kth node from end in a Linked List
- 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
- Make a loop at k-th position in a linked list
- Sorted insert in a doubly linked list with head and tail pointers
- Squareroot(n)-th node in a Linked List
- Linked List | Set 3 (Deleting a node)
- Remove last node of the linked list
- Remove every k-th node of the linked list
- Linked List | Set 2 (Inserting a node)
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.