VOOZH about

URL: https://www.geeksforgeeks.org/dsa/insert-a-node-after-a-given-node-in-linked-list/

⇱ Insert a Node after a given Node in Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insert a Node after a given Node in Linked List

Last Updated : 29 Jul, 2024

Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found".

Examples:

Input: LinkedList = 2 -> 3 -> 4 -> 5, newData = 1, key = 2
Output: LinkedList = 2 -> 1 -> 3 -> 4 -> 5

Input: LinkedList = 1 -> 3 -> 5 -> 7, newData = 1, key = 2
Output: Node not found

Approach: To solve the problem, follow the below idea:

If we want to insert a new node after a given node, we first locate that node. If the node is not found, print "Node not found". If we find it, we set the new node's next reference to point to the node that follows the given node. Then, we update the given node's next to point to the new node.

👁 Insertion-at-a-Specific-Position-of-the-Singly-Linked-List

Follow the below steps for inserting a node after a given node:

  • Traverse the linked list to find the given node.
  • If the given node is not found, print "Node not found".
  • Else if the given node is found, create a new node, say new_node initialized with the given data.
  • Make the next pointer of new_node as next of given node.
  • Update the next pointer of given node point to the new_node.

Below is the implementation of the approach:


Output
Original Linked List: 2 3 5 6 
Linked List after insertion: 2 3 4 5 6 

Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: