oneby7

Linked Lists Singly linked list basics

269. Delete the Tail

Medium

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

Each node holds a value and a pointer to the next node, and the tail's pointer is null. A list of one node has nothing left once its tail is gone, so return an empty list (null). An empty list has no tail, so return it as it is.

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.

Example 1

head
12-43071
output
12-4307

Input: head = [12, -4, 30, 7, 1]

Output: [12,-4,30,7]

Explanation: The tail holds 1. The node holding 7 now points to null, so it becomes the new tail. The head is still 12.

Example 2

929
head
92
output

Input: head = [9, 2, 9]

Output: [9,2]

Explanation: The tail holds 9, and so does the head. Only the last node goes; the head stays where it is.

Example 3

5

Input: head = [5]

Output: []

Explanation: The only node is both the head and the tail. Once it is gone the list is empty, so the answer is null.

Check your understanding

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

head = [5, 8, 2, 9]

Constraints

  • 0 ≤ 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.