980. Insert node before head in Doubly Linked List

Given the head of a doubly linked list and an integer X, insert a node with value X before the head of the linked list and return the head of the modified list.

Example 1:

Input: head = [1, 2, 3], X = 3

Output: head = [3, 1, 2, 3]

Explanation: 3 was added before the 1st node. Note that the head's value is changed.

Example 2:

Input: head = [5], X = 7

Output: head = [7, 5]

Now Your Turn!

Pick the correct output for the given input

Input: head = [2, 3], X = 10

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

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* insertBeforeHead(ListNode* head, int X) {
// Your code goes here
}
};
Test Case

Input:

X
Nums