medium +12 pts

Delete Middle Node

Given only access to a non-tail node, remove it from the singly linked list.

You are given a singly linked list represented by the custom class `ListNode` (defined below). Implement a function `delete_node(node: ListNode) -> None` that takes a reference to a node (not the head of the list) and removes that node from the linked list in-place. The node is guaranteed to be a non-tail node. You are **not** given the head of the list. The deletion should be done by copying the next node's value to the current node and bypassing the next node. Do not return anything. ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next ``` **Function signature:** `def delete_node(node: ListNode) -> None:` For testing, a helper function `delete_node_with_check(values, index)` is provided in the starter code. It builds a linked list from `values`, calls `delete_node` on the node at the given `index` (0-based), and returns the resulting list of values. You must implement `delete_node`; the helper is already complete and should not be modified.

Constraints

The linked list has at least 2 nodes. The `index` passed to the helper is always a valid index of a non-tail node. Time complexity: O(1) for `delete_node`. Space complexity: O(1).

Example

>>> head = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
>>> node = head.next.next  # node with value 3
>>> delete_node(node)
>>> # list becomes 1 -> 2 -> 4
>>> to_list(head)
[1, 2, 4]
12 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Copy the value of the next node into the current node.
Then set the current node's next pointer to skip the next node.
This trick works only because the node is guaranteed not to be the tail.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.