Delete Node in a Linked List

There is a singly linked list with unique values, and you must delete the node whose value is node. That node is never the last node. On LeetCode you are handed only the node itself, with no access to head, so you cannot reach the node before it. Codemia version: the judge needs to build the list, so deleteNode(head, node) receives head plus the value to delete and returns head. After locating the node, use the intended trick: copy the next value into it, then skip the next node.

30:00

Delete Node in a Linked List
medium
Free written solution
Topics
Companies

There is a singly linked list with unique values, and you must delete the node whose value is node. That node is never the last node. On LeetCode you are handed only the node itself, with no access to head, so you cannot reach the node before it. Codemia version: the judge needs to build the list, so deleteNode(head, node) receives head plus the value to delete and returns head. After locating the node, use the intended trick: copy the next value into it, then skip the next node.

Example 1:
Input: {"head":[4,5,1,9],"node":5}
Output: [4,1,9]
Constraints:
  • The number of nodes in the list is in the range [2,1000][2, 1000].

  • −1000≤Node.val≤1000-1000 \leq \text{Node.val} \leq 1000

  • The value of each node in the list is unique.

  • The node to delete is in the list and is not a tail node.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[4,5,1,9],"node":5}

target starts at the head. We need the node holding 5.

▲ target: node holding 5▲ target.next: donates its value■ unlinked
null4519target

Value to delete

5

Reading the list from head

[4, 5, 1, 9]

Variables
VariableValue
node5
target4
target.next5
DepthFunction Call
Stack empty
0/6