#237

Delete Node in a Linked List

pupil · 435 · lc medium +25 · verified · 83.6% accepted · 6,256 likes · top 95%

play →

Description

A node node within a singly-linked list head must be removed. You are given only a direct reference to node, not to the head of the list.

All node values are unique, and node is guaranteed not to be the last node.

Removing the node means:

- Its value must not appear in the resulting list.

- The list length decreases by one.

- All values before node stay in the same order.

- All values after node stay in the same order.

Custom testing:

- You will be given the full list head and the target node. node is never the last node and is always an actual node in the list.

- The judge builds the list and passes the node reference to your function.

- The output is the entire list after your function runs.

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 = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13