Delete Node in a Linked List

Medium · Linked Lists · Linked List

Problem

You are handed a reference to one node inside a singly linked list, but not the head of the list. Remove that node's value from the list.

The node is never the last one, and all values in the list are distinct. You cannot reach the node before it, so "deleting" means that afterwards:

In the tests, values is the whole list and target is the value of the node you receive; the grader builds the list, calls deleteNode with that node only, and reads the list back from its head.

Examples

Input: values = [3,8,1,6], target = 8
Output: [3,1,6]

The node holding 8 takes the value 1 from the next node and skips that node, so 8 disappears and the list reads 3, 1, 6.

Input: values = [10,20], target = 10
Output: [20]

The head node takes the value 20 and drops the old second node.

Input: values = [4,5,9,2], target = 9
Output: [4,5,2]

The node before the tail copies 2 and unlinks the tail.

Constraints

Approaches

Follow-up

Why can the node not be the tail? There is no successor to copy, and without the previous node nothing can drop the tail. Some designs keep a dummy sentinel at the end of every list for exactly this reason: then every real node has a successor.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…