#371Medium· asked at 2 companies
Deletion of the tail of Linked List
Problem
Given the head of a singly linked list, delete the last node and return the head. If the list is empty or has one node, return null.
Input / Output
- Input: head of a singly linked list.
- Output: head after deleting the tail.
Examples
Example 1
Input: 1 -> 2 -> 3
Output: 1 -> 2
Example 2
Input: 9
Output: empty
Example 3
Input: 4 -> 8
Output: 4
Constraints
0 <= number of nodes <= 10^5
Approach
Because nodes only point forward, deleting the tail requires the second-to-last node:
- If
headisnullorhead.nextisnull, returnnull. - Walk
curuntilcur.next.nextisnull—curis now the second-to-last node. - Set
cur.next = null.
Unlike a doubly linked list (where a stored tail pointer makes this O(1)), a singly linked list needs the full traversal even if a tail pointer exists, because the new tail's predecessor is unknown. Interviewers use this contrast to ask when would you choose a doubly linked list?
Complexity
- Time: O(n)
- Space: O(1)
Reference solution (Python)
def delete_tail(head):
if head is None or head.next is None:
return None
cur = head
while cur.next.next:
cur = cur.next
cur.next = None
return head
Test cases
| Input | Expected |
|---|---|
1->2->3 | 1->2 |
9 | None |
4->8 | 4 |
| empty | None |