Given a node's reference within a doubly linked list and an integer X, insert a node with value X before the given node in the linked list while preserving the list's integrity.
You will only be given the node's reference, not the head of the list. It is guaranteed that the given node will not be the head of the list.
Input: head -> 1 <-> 2 <-> 6, node = 2, X = 7
Output: head -> 1 <-> 7 <-> 2 <-> 6
Explanation: Note that the head was not given to the function.
Input: head -> 7 <-> 5 <-> 5, node = 5 (node 3), X = 10
Output: head -> 7 <-> 5 <-> 10 <-> 5
Explanation: The last node with value 5 was referenced, thus the new node was added before the last node.
Input: head -> 7 <-> 6 <-> 5, node = 5, X = 10
#include <bits/stdc++.h>
using namespace std;
// Definition of doubly linked list
struct ListNode
{
int val;
ListNode *next;
ListNode *prev;
ListNode()
{
val = 0;
next = NULL;
prev = NULL;
}
ListNode(int data1)
{
val = data1;
next = NULL;
prev = NULL;
}
ListNode(int data1, ListNode *next1, ListNode *prev1)
{
val = data1;
next = next1;
prev = prev1;
}
};
// Solution class
class Solution {
public:
/* Function to insert a new node before
given node in a doubly linked list */
void insertBeforeGivenNode(ListNode* node, int X) {
// Get node before the given node
ListNode* prev = node->prev;
// Create new node
ListNode* newNode = new ListNode(X, node, prev);
// Connect newNode
prev->next = newNode;
node->prev = newNode;
// void function to just update
return;
}
};
// Helper Function to convert an array to a doubly linked list
ListNode* arrayToLinkedList(vector<int> &nums) {
// If array is empty, return nullptr
if (nums.empty()) return nullptr;
// Create head node with first element of the array
ListNode* head = new ListNode(nums[0]);
// Initialize 'prev' to the head node
ListNode* prev = head;
for (int i=1; i < nums.size(); i++) {
// Create a new node
ListNode* temp = new ListNode(nums[i], nullptr, prev);
// Update 'next' pointer
prev->next = temp;
// Move 'prev' to newly created node
prev = temp;
}
// Return head
return head;
}
// Helper Function to print the linked list
void printLL(ListNode* head) {
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
vector<int> nums = {1, 2, 4, 5};
// Creating the doubly linked list from given array
ListNode* head = arrayToLinkedList(nums);
// Node before which the new node must be inserted
ListNode* node = head-> next-> next;
// Print the Original list
cout << "Original List: ";
printLL(head);
// Create an instance of Solution class
Solution sol;
/* Function call to insert a new node before
given node in a doubly linked list */
sol.insertBeforeGivenNode(node, 3);
// Print the Modified list
cout << "Modified list: ";
printLL(head);
return 0;
}
// Definition of doubly linked list
class ListNode {
int val;
ListNode next;
ListNode prev;
ListNode() {
val = 0;
next = null;
prev = null;
}
ListNode(int data1) {
val = data1;
next = null;
prev = null;
}
ListNode(int data1, ListNode next1, ListNode prev1) {
val = data1;
next = next1;
prev = prev1;
}
}
// Solution class
class Solution {
/* Function to insert a new node before
given node in a doubly linked list */
public void insertBeforeGivenNode(ListNode node, int X) {
// Get node before the given node
ListNode prev = node.prev;
// Create new node
ListNode newNode = new ListNode(X, node, prev);
// Connect newNode
prev.next = newNode;
node.prev = newNode;
// void function to just update
return;
}
}
// Class main
class Main {
// Helper Function to convert an array to a doubly linked list
private static ListNode arrayToLinkedList(int[] nums) {
// If array is empty, return null
if (nums.length == 0) return null;
// Create head node with first element of the array
ListNode head = new ListNode(nums[0]);
// Initialize 'prev' to the head node
ListNode prev = head;
for (int i = 1; i < nums.length; i++) {
// Create a new node
ListNode temp = new ListNode(nums[i], null, prev);
// Update 'next' pointer
prev.next = temp;
// Move 'prev' to newly created node
prev = temp;
}
// Return head
return head;
}
// Helper Function to print the linked list
private static void printLL(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
// main method
public static void main(String[] args) {
int[] nums = {1, 2, 4, 5};
// Creating the doubly linked list from given array
ListNode head = arrayToLinkedList(nums);
// Node before which the new node must be inserted
ListNode node = head.next.next;
// Print the Original list
System.out.print("Original List: ");
printLL(head);
// Create an instance of Solution class
Solution sol = new Solution();
/* Function call to insert a new node before
given node in a doubly linked list */
sol.insertBeforeGivenNode(node, 3);
// Print the Modified list
System.out.print("Modified list: ");
printLL(head);
}
}
# Definition of doubly linked list
class ListNode:
def __init__(self, data1=0, next1=None, prev1=None):
self.val = data1
self.next = next1
self.prev = prev1
# Solution class
class Solution:
''' Function to insert a new node before
given node in a doubly linked list '''
def insertBeforeGivenNode(self, node, X):
# Get node before the given node
prev = node.prev
# Create new node
newNode = ListNode(X, node, prev)
# Connect newNode
prev.next = newNode
node.prev = newNode
# void function to just update
return
# Helper Function to convert an array to a doubly linked list
def arrayToLinkedList(nums):
# If array is empty, return None
if not nums:
return None
# Create head node with first element of the array
head = ListNode(nums[0])
# Initialize 'prev' to the head node
prev = head
for i in range(1, len(nums)):
# Create a new node
temp = ListNode(nums[i], None, prev)
# Update 'next' pointer
prev.next = temp
# Move 'prev' to newly created node
prev = temp
# Return head
return head
# Helper Function to print the linked list
def printLL(head):
while head is not None:
print(head.val, end=" ")
head = head.next
print()
if __name__ == "__main__":
nums = [1, 2, 4, 5]
# Creating the doubly linked list from given array
head = arrayToLinkedList(nums)
# Node before which the new node must be inserted
node = head.next.next
# Print the Original list
print("Original List: ", end="")
printLL(head)
# Create an instance of Solution class
sol = Solution()
''' Function call to insert a new node before
given node in a doubly linked list '''
sol.insertBeforeGivenNode(node, 3)
# Print the Modified list
print("Modified list: ", end="")
printLL(head)
// Definition of doubly linked list
class ListNode {
constructor(data1 = 0, next1 = null, prev1 = null) {
this.val = data1;
this.next = next1;
this.prev = prev1;
}
}
// Solution class
class Solution {
/* Function to insert a new node before
given node in a doubly linked list */
insertBeforeGivenNode(node, X) {
// Get node before the given node
let prev = node.prev;
// Create new node
let newNode = new ListNode(X, node, prev);
// Connect newNode
prev.next = newNode;
node.prev = newNode;
// void function to just update
return;
}
}
// Helper Function to convert an array to a doubly linked list
function arrayToLinkedList(nums) {
// If array is empty, return null
if (nums.length === 0) return null;
// Create head node with first element of the array
let head = new ListNode(nums[0]);
// Initialize 'prev' to the head node
let prev = head;
for (let i = 1; i < nums.length; i++) {
// Create a new node
let temp = new ListNode(nums[i], null, prev);
// Update 'next' pointer
prev.next = temp;
// Move 'prev' to newly created node
prev = temp;
}
// Return head
return head;
}
// Helper Function to print the linked list
function printLL(head) {
while (head !== null) {
process.stdout.write(head.val + " ");
head = head.next;
}
console.log();
}
const main = () => {
const nums = [1, 2, 4, 5];
// Creating the doubly linked list from given array
let head = arrayToLinkedList(nums);
// Node before which the new node must be inserted
let node = head.next.next;
// Print the Original list
console.log("Original List: ");
printLL(head);
// Create an instance of Solution class
let sol = new Solution();
/* Function call to insert a new node before
given node in a doubly linked list */
sol.insertBeforeGivenNode(node, 3);
// Print the Modified list
console.log("Modified list: ");
printLL(head);
}
main();
Q: Why does this approach work in O(1)?
A: Unlike singly linked lists (O(n) for backward traversal), DLLs allow direct access to prev, making insertion constant time.
Q: Why do we NOT need access to the head?
A: Since we are given a node inside the list, and the node before it is guaranteed to exist, we don’t need the head.
Q: How would this change if the list was a singly linked list (SLL)?
A: O(n) complexity instead of O(1), since we must traverse from head to find prev_node.
Q: How can we modify this to insert X after given_node instead?
A: Update given_node->next instead of prev.