oneby7

Linked Lists Fast and slow pointers

295. Delete the Middle Node of a Linked List

Medium

You are given head, the first node of a singly linked list. Delete the middle node of the list, and return the head of the list that is left.

Number the nodes from 0, starting at the head. In a list of n nodes, the middle node is the node at index n / 2, rounded down. When n is odd, that node has as many nodes before it as after it. When n is even, two nodes share the centre, and the middle is the second of them: in a list of 4 nodes it is the node at index 2, the third node.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the list you return the same way. A list of one node loses its only node, so return null, which shows as [].

Example 1

head
310-2851
output
310-251

Input: head = [3, 10, -2, 8, 5, 1]

Output: [3,10,-2,5,1]

Explanation: Six nodes, so the middle is at index 6 / 2 = 3, the node holding 8. The nodes holding -2 and 8 share the centre, and the middle is the second of them. Deleting it links -2 straight to 5.

Example 2

head
74926
output
7426

Input: head = [7, 4, 9, 2, 6]

Output: [7,4,2,6]

Explanation: Five nodes, so the middle is at index 5 / 2 = 2, rounded down. That node holds 9, with two nodes on each side of it.

Example 3

-8

Input: head = [-8]

Output: []

Explanation: The middle of one node is the node at index 0, the head. Deleting it leaves no nodes, so the answer is null.

Check your understanding

Work out the answer for this input before you write any code.

head = [6, 1, 6, 3]

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.