183. Delete Node in a Linked List O(1)

Write a function to delete a node in a singly-linked list, given only access to that node.

You will not be given access to the head of the list, instead you will be given a reference to the node that needs to be deleted. It is guaranteed that the node to be deleted is not the tail of the list.

You must modify the linked list in-place without returning anything.

Example 1:

Input: head = [4,5,1,9], node = 5

Output: [4,1,9]

Explanation:

You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

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

Output: [1,2,4]

Explanation:

You are given the third node with value 3, remove it in-place.

Now Your Turn!

Pick the correct output for the given input

Input: head = [1,2], node = 1

Still unsure what the problem is asking ?

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

Constraints:

  • The number of nodes in the list is in the range [2, 1000]
  • -1000 <= Node.val <= 1000
  • The given node is not the tail and is guaranteed to be in the list
  • The linked list will have at least two nodes

Fun Facts

0
/*
Definition of singly linked list:
class ListNode{
public:
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
*/
 
class Solution {
public:
void deleteNode(ListNode* node) {
// Your code goes here
}
};
Test Case

Input:

Head
Node