VOOZH about

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

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


  • Courses
  • Tutorials
  • Interview Prep

Insert a Node after a given node in Doubly Linked List

Last Updated : 7 Aug, 2024

Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list.

Examples:

Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2
Output: Linked List = 1 <-> 2 <-> 3 <-> 4
Explanation: New node 3 is inserted after key, that is node 2.

Input: Linked List = 1 <-> 2, newData = 4, key = 2
Output: Linked List = 1 <-> 2 <-> 4
Explanation: New node 4 is inserted after key, that is node 2.

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

To insert a new node after a given node, we first find the given node in the doubly linked list. If the given node is not found, return the original linked list. Otherwise if the given node is found, say current node, we create a new node with new data and update its pointers: Update the previous pointer of new node to the current node and the next pointer of new node to the current node' s next. Then, update the next pointer of current node to the new node. Finally, if the new node is not the last node of the linked list, then we update the update previous pointer of new node’s next node to new node.

👁 Insertion-after-a-given-node-in-Doubly-Linked-List
Insert node 3 after given node 2 in Doubly Linked List

To insert a new node after a specific node,

  • Find the given node in the doubly linked list, say curr.
  • Once we find it, create a new node with the new data, say new_node.
  • Update the new node’s previous pointer to given node and new node’s next pointer to the given node’s next, new_node->prev = curr and new_node->next = curr->next.
  • Then, we update the next pointer of given node with new node, curr->next = new_node.
  • Also, if the new node is not the last node of the linked list, then update previous pointer of new node’s next node to new node, new_node->next->prev = new_node.

Output
Original Linked List: 1 3 4
Inserting Node with data 2 after node 1: 1 2 3 4

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

Comment
Article Tags: