Given the head of a doubly linked list and two integers X and K, insert a new node with value X, before the Kth node of the linked list and return the head of the modified linked list.
Input: head -> 1 <-> 3 <-> 5, X = 7, K = 2
Output: head -> 1 <-> 7 <-> 3 <-> 5
Explanation: A node with value 7 was added before the 2nd node.
Input: head -> 5, X = 7, K = 1
Output: head -> 7 <-> 5
Explanation: A node with value 7 was added, note that the head was changed.
Input: head -> 4 <-> 5, X = 10, K = 2
#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 node before the
Kth node in a doubly linked list */
ListNode* insertBeforeKthPosition(ListNode* head, int X, int K) {
// If node has to be inserted before the head
if (K == 1) {
ListNode* newHead = new ListNode(X, head, nullptr);
head->prev = newHead;
return newHead;
}
// Temporary pointer
ListNode* temp = head;
// Reach kth node
int count = 0;
while (temp != nullptr) {
count++;
// If kth node is reached, Break out of the loop
if (count == K) break;
// Otherwise Keep moving temp forward
temp = temp->next;
}
// Track the node
ListNode* prev = temp->prev;
// Create new node with data as X
ListNode* newNode = new ListNode(X, temp, prev);
// Join new node
prev->next = newNode;
temp->prev = newNode;
// Return head
return head;
}
};
// 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, 3, 5};
// Creating the doubly linked list from given array
ListNode* head = arrayToLinkedList(nums);
// Print the Original list
cout << "Original List: ";
printLL(head);
// Create an instance of Solution class
Solution sol;
/* Function call to insert a node before the
Kth node in a doubly linked list */
head = sol.insertBeforeKthPosition(head, 4, 4);
// 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 node before the
Kth node in a doubly linked list */
public ListNode insertBeforeKthPosition(ListNode head, int X, int K) {
// If node has to be inserted before the head
if (K == 1) {
ListNode newHead = new ListNode(X, head, null);
head.prev = newHead;
return newHead;
}
// Temporary pointer
ListNode temp = head;
// Reach Kth node
int count = 0;
while (temp != null) {
count++;
// If Kth node is reached, Break out of the loop
if (count == K) break;
// Otherwise Keep moving temp forward
temp = temp.next;
}
// Track the node
ListNode prev = temp.prev;
// Create new node with data as X
ListNode newNode = new ListNode(X, temp, prev);
// Join new node
prev.next = newNode;
temp.prev = newNode;
// Return head
return head;
}
}
// 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, 3, 5};
// Creating the doubly linked list from given array
ListNode head = arrayToLinkedList(nums);
// 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 node before the
Kth node in a doubly linked list */
head = sol.insertBeforeKthPosition(head, 4, 4);
// 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 node before the
Kth node in a doubly linked list '''
def insertBeforeKthPosition(self, head, X, K):
# If node has to be inserted before the head
if K == 1:
newHead = ListNode(X, head, None)
head.prev = newHead
return newHead
# Temporary pointer
temp = head
# Reach Kth node
count = 0
while temp is not None:
count += 1
# If Kth node is reached, Break out of the loop
if count == K:
break
# Otherwise Keep moving temp forward
temp = temp.next
# Track the node
prev = temp.prev
# Create new node with data as X
newNode = ListNode(X, temp, prev)
# Join new node
prev.next = newNode
temp.prev = newNode
# Return head
return head
# 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, 3, 5]
# Creating the doubly linked list from given array
head = arrayToLinkedList(nums)
# Print the Original list
print("Original List: ", end="")
printLL(head)
# Create an instance of Solution class
sol = Solution()
''' Function call to insert a node before the
Kth node in a doubly linked list '''
head = sol.insertBeforeKthPosition(head, 4, 4)
# 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 node before the
Kth node in a doubly linked list */
insertBeforeKthPosition(head, X, K) {
// If node has to be inserted before the head
if (K === 1) {
let newHead = new ListNode(X, head, null);
head.prev = newHead;
return newHead;
}
// Temporary pointer
let temp = head;
// Reach Kth node
let count = 0;
while (temp !== null) {
count++;
// If Kth node is reached, Break out of the loop
if (count === K) break;
// Otherwise Keep moving temp forward
temp = temp.next;
}
// Track the node
let prev = temp.prev;
// Create new node with data as X
let newNode = new ListNode(X, temp, prev);
// Join new node
prev.next = newNode;
temp.prev = newNode;
// Return head
return head;
}
}
// 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, 3, 5];
// Creating the doubly linked list from given array
let head = arrayToLinkedList(nums);
// 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 node before the
Kth node in a doubly linked list */
head = sol.insertBeforeKthPosition(head, 4, 4);
// Print the Modified list
console.log("Modified list: ");
printLL(head);
}
main();
Q: What happens if the list is empty (head = NULL)?
A: Insert X as the only node, making it the new head.
Q: Can we insert at the end if K > length of list?
A: Yes! If K exceeds the number of nodes, append X at the tail.
Q: How would this approach change if the list were a singly linked list?
A: Finding Kth node remains O(K), but insertion is harder since there’s no prev pointer.
Q: What if K was given as a negative index (e.g., -1 for inserting before the last node)?
A: Convert K into a 1-based position from the end using count - |K|.