985. Insert node before tail in Doubly Linked List

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

Example 1:

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

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

Explanation: 3 was added before the last node.

Example 2:

Input: head = [4], X = 6

Output: head = [6, 4]

Explanation: 6 was added before 4, note that the head was changed as a result.

Now Your Turn!

Pick the correct output for the given input

Input: head = [4, 5], X = 6

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

Input:

X
Nums