971. Insert node before (kth node) in Doubly Linked List

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.

Example 1:

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.

Example 2:

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.

Now Your Turn!

Pick the correct output for the given input

Input: head = [4, 5], X = 10, K = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • n == Number of nodes in the linked list
  • 1 <= n <= 100
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100
  • 1 <= K <= n

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
class ListNode
{
* Definition for doubly-linked list.
* public:
* int data;
* ListNode *prev;
* ListNode *next;
* ListNode() : data(0), prev(nullptr), next(nullptr) {}
* ListNode(int x) : data(x), prev(nullptr), next(nullptr) {}
* ListNode(int x, ListNode *prev, ListNode *next) : data(x), prev(prev), next(next) {}
};
*/
 
class Solution {
public:
ListNode* insertBeforeKthPosition(ListNode* head, int X, int K) {
// Your code goes here
}
};
Test Case

Input:

K
X
Nums