There is a singly linked list, and we want to delete one node node in it.
You are given the node to be deleted, node. You are not given access to the first node of the list.
All the values in the linked list are unique, and the given node is guaranteed not to be the last node in the list.
Delete the given node. Deleting it does not mean removing it from memory. It means:
-
The value of the given node no longer exists in the linked list.
-
The number of nodes in the linked list decreases by one.
-
All the values before
node
stay in the same order.
-
All the values after
node
stay in the same order.
Function Signature
def delete_node(node: ListNode) -> None:
Rules
-
ListNode
has two fields:
val
, an integer, and
next
, the next
ListNode
or
None
at the tail.
-
In the examples,
head
is the list of node values from first to last, and
val
is the value of the node to delete. The judge builds the linked list from
head
, calls
delete_node
with the node whose value is
val
, and then reads the values starting from the original first node. That list of values is the expected output.
-
Modify the list in place and return nothing.
Constraints
-
2 <= len(head) <= 1000
-
-1000 <= Node.val <= 1000
-
The value of each node in the list is unique.
-
The node to be deleted is in the list and is not the tail node.
Examples
Example 1
Input: head = [4, 5, 1, 9], val = 5
Output: [4, 1, 9]
The list is 4 -> 5 -> 1 -> 9 and the given node holds 5. After the deletion, reading from the first node gives 4 -> 1 -> 9.
Example 2
Input: head = [4, 5, 1, 9], val = 1
Output: [4, 5, 9]
The given node holds 1. Removing it leaves 4 -> 5 -> 9, with the values on both sides in their original order.
Example 3
Input: head = [1, 2], val = 1
Output: [2]
The node to delete is the first node of a two-node list. Afterward the list has one node, and its value is 2.