891. Delete the element with value X

Given the head of a singly linked list and an integer X, delete the node with value X and return the head of the modified list.

Example 1:

Input: linkedList = [3, 4, 5], X = 5

Output: [3, 4]

Explanation:

The node with value 5 was removed.

Example 2:

Input: linkedList = [3, 4, 5], X = 7

Output: [3, 4, 5]

Explanation:

No nodes were removed.

Now Your Turn!

Pick the correct output for the given input

Input: linkedList = [3, 4, 5], X = 3

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 <= 1000
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100
  • Number of nodes with value X is either 0 or 1

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/*
Definition of singly linked list:
class ListNode{
public:
int data;
ListNode *next;
ListNode() : data(0), next(nullptr) {}
ListNode(int x) : data(x), next(nullptr) {}
ListNode(int x, ListNode *next) : data(x), next(next) {}
};
*/
 
class Solution {
public:
ListNode* deleteNodeWithValueX(ListNode* &head, int X) {
//your code goes here
}
};
Test Case

Input:

X
Linked List