Insert a Node before a given node in Doubly Linked List
Last Updated :
07 Aug, 2024
Given a Doubly Linked List, the task is to insert a new node before a given node in the linked list.
Examples:
Input: Linked List = 1 <-> 3 <-> 4, newData = 2, key = 3
Output: Linked List = 1 <-> 2 <-> 3 <-> 4
Explanation: New node with data 2 is inserted before the node with data = 3
Input: Linked List = 2 <-> 3, newData = 1, key = 2
Output: Linked List = 1 <-> 2 <-> 3
Explanation: New node with data 1 is inserted before the node with data = 2
Approach:
To insert a new node before 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's prev and the next pointer of new node to the current node. Now, check if the current node is not the head of the linked list, then we update the update next pointer of new node’s prev node to new node. Finally, update the prev pointer of current node to the new node.
Insert node 2 before node 3 in Doubly Linked ListTo insert a new node before a specific node,
- Find the given node in the linked list, say curr.
- Once we find it, we create a new node, say new_node with the new data.
- Set the new node’s previous pointer to given node’s prev and new node’s next pointer to the given node, new_node->prev = curr->prev and new_node->next = curr.
- Check if the given node is not the head of the linked list,
- If given node is the head, update head of the linked list to new_node, head = new_node.
- Else if the given node is not the head, update next pointer of new node’s prev node to new node, new_node->prev->next = new_node.
- Finally, we update the prev pointer of given node with new node, curr->prev = new_node.
C++
// C++ Program to insert a node before a given node of doubly linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next, *prev;
Node(int new_data) {
data = new_data;
next = prev = NULL;
}
};
// Function to insert a new node before a given node
// in doubly linked list
Node *insertBefore(Node *head, int key, int new_data) {
Node *curr = head;
// Iterate over Linked List to find the key
while (curr != NULL) {
if (curr->data == key)
break;
curr = curr->next;
}
// if curr becomes null means, given key is not
// found in linked list
if (curr == NULL)
return head;
// Create a new node
Node *new_node = new Node(new_data);
// Set prev of new node to prev of given node
new_node->prev = curr->prev;
// Set next of new node to given node
new_node->next = curr;
// Update next of given node's prev to new node
if (curr->prev != NULL) {
new_node->prev->next = new_node;
}
else {
// If the current node is the head, update the head
head = new_node;
}
// Update prev of given node to new node
curr->prev = new_node;
// Return the head of the doubly linked list
return head;
}
void printList(Node *head) {
Node *curr = head;
while (curr != NULL) {
cout << " " << curr->data;
curr = curr->next;
}
cout << endl;
}
int main() {
// Create a harcoded doubly linked list:
// 1 <-> 3 <-> 4
Node *head = new Node(1);
head->next = new Node(3);
head->next->prev = head;
head->next->next = new Node(4);
head->next->next->prev = head->next;
// Print the original list
cout << "Original Linked List:";
printList(head);
// Insert a new node before node with data 3
cout << "Inserting Node with data 2 before node 3:";
int data = 2;
int key = 3;
head = insertBefore(head, key, data);
// Print the updated list
printList(head);
return 0;
}
C
// C Program to insert a node after a given node of doubly linked list
#include <stdio.h>
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
// Function to create a new node with the given data
struct Node *createNode(int new_data) {
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
// Function to insert a new node before a given node
struct Node* insertBefore(struct Node *head, int key, int new_data) {
struct Node *curr = head;
// Iterate over Linked List to find the key
while (curr != NULL) {
if (curr->data == key)
break;
curr = curr->next;
}
// If curr becomes NULL, the given key is not found in the linked list
if (curr == NULL)
return head;
// Create a new node
struct Node *new_node = createNode(new_data);
// Set prev of new node to prev of given node
new_node->prev = curr->prev;
// Set next of new node to given node
new_node->next = curr;
// Update next of given node's prev to new node
if (curr->prev != NULL) {
curr->prev->next = new_node;
} else {
// If the current node is the head, update the head
head = new_node;
}
// Update prev of given node to new node
curr->prev = new_node;
return head;
}
void printList(struct Node *head) {
struct Node *curr = head;
while (curr != NULL) {
printf(" %d", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
// Create a hardcoded doubly linked list:
// 1 <-> 3 <-> 4
struct Node *head = createNode(1);
head->next = createNode(3);
head->next->prev = head;
head->next->next = createNode(4);
head->next->next->prev = head->next;
// Print the original list
printf("Original Linked List:");
printList(head);
// Insert a new node before node with data 3
printf("Inserting Node with data 2 before node 3:");
int data = 2;
int key = 3;
head = insertBefore(head, key, data);
// Print the updated list
printList(head);
return 0;
}
Java
// Java Program to insert a node before a given node of
// doubly linked list
class Node {
int data;
Node next, prev;
Node(int newData) {
data = newData;
next = prev = null;
}
}
public class GFG {
// Function to insert a new node before a given node
public static Node insertBefore(Node head, int key,
int newData) {
Node curr = head;
// Iterate over Linked List to find the key
while (curr != null) {
if (curr.data == key) {
break;
}
curr = curr.next;
}
// If curr becomes null, the given key is not found
// in the linked list
if (curr == null) {
return head;
}
// Create a new node
Node newNode = new Node(newData);
// Set prev of new node to prev of given node
newNode.prev = curr.prev;
// Set next of new node to given node
newNode.next = curr;
// Update next of given node's prev to new node
if (curr.prev != null) {
curr.prev.next = newNode;
}
else {
// If the current node is the head, update the
// head
head = newNode;
}
// Update prev of given node to new node
curr.prev = newNode;
return head;
}
// Function to print the list
public static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(" " + curr.data);
curr = curr.next;
}
System.out.println();
}
// Main function
public static void main(String[] args) {
// Create a hardcoded doubly linked list: 1 <-> 3 <-> 4
Node head = new Node(1);
head.next = new Node(3);
head.next.prev = head;
head.next.next = new Node(4);
head.next.next.prev = head.next;
// Print the original list
System.out.print("Original Linked List: ");
printList(head);
// Insert a new node before node with data 3
System.out.print(
"Inserting Node with data 2 before node 3: ");
int data = 2;
int key = 3;
head = insertBefore(head, key, data);
// Print the updated list
printList(head);
}
}
Python
# Python Program to insert a node before a given node of
# doubly linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Function to insert a new node before a given node
# in doubly linked list
def insert_before(head, key, new_data):
curr = head
# Iterate over Linked List to find the key
while curr is not None:
if curr.data == key:
break
curr = curr.next
# If curr becomes None, the given key is not found in the linked list
if curr is None:
return head
# Create a new node
new_node = Node(new_data)
# Set prev of new node to prev of given node
new_node.prev = curr.prev
# Set next of new node to given node
new_node.next = curr
# Update next of given node's prev to new node
if curr.prev is not None:
curr.prev.next = new_node
else:
# If the current node is the head, update the head
head = new_node
# Update prev of given node to new node
curr.prev = new_node
return head
def print_list(head):
curr = head
while curr is not None:
print(f" {curr.data}", end="")
curr = curr.next
print()
if __name__ == "__main__":
# Create a hardcoded doubly linked list:
# 1 <-> 3 <-> 4
head = Node(1)
head.next = Node(3)
head.next.prev = head
head.next.next = Node(4)
head.next.next.prev = head.next
# Print the original list
print("Original Linked List:", end="")
print_list(head)
# Insert a new node before node with data 3
print("Inserting Node with data 2 before node 3:", end="")
data = 2
key = 3
head = insert_before(head, key, data)
# Print the updated list
print_list(head)
C#
// C# Program to insert a node before a given node of
// doubly linked list
using System;
class Node
{
public int Data;
public Node Next;
public Node Prev;
public Node(int data) {
Data = data;
Next = null;
Prev = null;
}
}
class GFG {
// Function to insert a new node before a given node in doubly linked list
static Node InsertBefore(Node head, int key, int newData) {
Node curr = head;
// Iterate over Linked List to find the key
while (curr != null) {
if (curr.Data == key)
break;
curr = curr.Next;
}
// if curr becomes null means, given key is not found in linked list
if (curr == null)
return head;
// Create a new node
Node newNode = new Node(newData);
// Set prev of new node to prev of given node
newNode.Prev = curr.Prev;
// Set next of new node to given node
newNode.Next = curr;
// Update next of given node's prev to new node
if (curr.Prev != null) {
curr.Prev.Next = newNode;
}
else {
// If the current node is the head, update the head
head = newNode;
}
// Update prev of given node to new node
curr.Prev = newNode;
// Return the head of the doubly linked list
return head;
}
static void PrintList(Node head) {
Node curr = head;
while (curr != null) {
Console.Write(curr.Data + " ");
curr = curr.Next;
}
Console.WriteLine();
}
static void Main() {
// Create a hardcoded doubly linked list:
// 1 <-> 3 <-> 4
Node head = new Node(1);
head.Next = new Node(3);
head.Next.Prev = head;
head.Next.Next = new Node(4);
head.Next.Next.Prev = head.Next;
// Print the original list
Console.WriteLine("Original Linked List:");
PrintList(head);
// Insert a new node before node with data 3
Console.WriteLine("Inserting Node with data 2 before node 3:");
int data = 2;
int key = 3;
head = InsertBefore(head, key, data);
// Print the updated list
PrintList(head);
}
}
JavaScript
// JavaScript Program to insert a node before a given node of
// doubly linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
// Function to insert a new node before a given node in a doubly linked list
function insertBefore(head, key, newData) {
let curr = head;
// Iterate over Linked List to find the key
while (curr !== null) {
if (curr.data === key) {
break;
}
curr = curr.next;
}
// if curr becomes null means, given key is not found in linked list
if (curr === null) {
return head;
}
// Create a new node
const newNode = new Node(newData);
// Set prev of new node to prev of given node
newNode.prev = curr.prev;
// Set next of new node to given node
newNode.next = curr;
// Update next of given node's prev to new node
if (curr.prev !== null) {
curr.prev.next = newNode;
} else {
// If the current node is the head, update the head
head = newNode;
}
// Update prev of given node to new node
curr.prev = newNode;
// Return the head of the doubly linked list
return head;
}
function printList(head) {
let curr = head;
let result = '';
while (curr !== null) {
result += ` ${curr.data}`;
curr = curr.next;
}
console.log(result);
}
// Create a hardcoded doubly linked list:
// 1 <-> 3 <-> 4
const head = new Node(1);
head.next = new Node(3);
head.next.prev = head;
head.next.next = new Node(4);
head.next.next.prev = head.next;
// Print the original list
console.log("Original Linked List:");
printList(head);
// Insert a new node before node with data 3
console.log("Inserting Node with data 2 before node 3:");
const newData = 2;
const key = 3;
const newHead = insertBefore(head, key, newData);
// Print the updated list
printList(newHead);
OutputOriginal Linked List: 1 3 4
Inserting Node with data 2 before node 3: 1 2 3 4
Time Complexity: O(N), where N is the number of nodes in doubly linked list
Auxiliary Space: O(1)
Similar Reads
Insert a Node after a given node in Doubly Linked List 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 = 2Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node 3 is inserted after key, that is node 2.In
11 min read
Insert a node in Linked List before a given node Given a linked list, the task is to insert a new node with a specified value into a linked list before a node with a given key.ExamplesInput: head: 1 -> 2 -> 3 -> 4 -> 5 , newData = 6, key = 2Output: 1 -> 6 -> 2 -> 3 -> 4 -> 5 Explanation: After inserting node with value 6
15+ min read
Insert a Node after a given Node in Linked List 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 = 2Output: LinkedList = 2 -> 1 -> 3 -> 4 -> 5I
11 min read
Insert a Node at the end of Doubly Linked List Given a Doubly Linked List, the task is to insert a new node at the end of the linked list.Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4Input: Linked List = NULL, NewNode = 1Output: Linked List = 1Approach: Inserting
9 min read
Insert a Node at a specific position in Doubly Linked List Given a Doubly Linked List, the task is to insert a new node at a specific position in the linked list. Examples:Input: Linked List = 1 <-> 2 <-> 4, newData = 3, position = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data = 3 is inserted at posi
13 min read
Insert value in sorted way in a sorted doubly linked list Given a Sorted Doubly Linked List in (non-decreasing order) and an element x, the task is to insert the element x into the correct position in the Sorted Doubly Linked List. Example:Input: LinkedList = 3<->5<->8<->10<->12 , x = 9Output: 3<->5<->8<->9<-
9 min read
Insert a Node at Front/Beginning of a Linked List Given a linked list, the task is to insert a new node at the beginning/start/front of the linked list.Example:Input: LinkedList = 2->3->4->5, NewNode = 1Output: 1 2 3 4 5Input: LinkedList = 2->10, NewNode = 1Output: 1 2 10Approach:To insert a new node at the front, we create a new node a
8 min read
Insert Node at the End of a Linked List Given a linked list, the task is to insert a new node at the end of the linked list.Examples:Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1Approach:Â Inserting at the end invol
9 min read
Insertion in a Doubly Linked List Inserting a new node in a doubly linked list is very similar to inserting new node in linked list. There is a little extra work required to maintain the link of the previous node. In this article, we will learn about different ways to insert a node in a doubly linked list.Table of ContentInsertion a
6 min read
Javascript Program For Deleting A Node In A Doubly Linked List Pre-requisite: Doubly Link List Set 1| Introduction and InsertionWrite a function to delete a given node in a doubly-linked list. Original Doubly Linked List Approach: The deletion of a node in a doubly-linked list can be divided into three main categories: After the deletion of the head node. After
4 min read