Given a node of Linked List N and a value K, the task is to insert the node with value K in the linked list before the given node N.
Structure of the Node:
5 8 6
In the given problem there might be two cases:
- Given node is the head node.
- Given node is any valid node except the head.
When given Node is the Head Node:
The idea is to create a new node with the given value K. Then the next part of the new node will be updated with the pointer head. And finally, the head will be updated with the new node’s address. Below is the image of the same:
When given Node is any valid node except head node:
The simplest approach is to traverse the given linked list to search the previous node of the given node. Then, create the new node with the given value K.Now, update the next part of the new node with the address of the given node and the next part of the previous node with the address of the new node. Below is an illustration of the approach with the help of image:
Below is the implementation of the above approach:
5 8 6
Time Complexity: O(N)
Auxiliary Space: O(1)
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.
- Insert node into the middle of the linked list
- Insert a node at a specific position in a linked list
- Create new linked list from two given linked list with greater element at each node
- Given a linked list which is sorted, how will you insert in sorted way
- Count of all possible Paths in a Tree such that Node X does not appear before Node Y
- 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
- Insert N elements in a Linked List one after other at middle position
- Insert a whole linked list into other at k-th position
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Check if a linked list is Circular Linked List
- Insert a node after the n-th node from the end
- Delete a given node in Linked List under given constraints
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.