#366Medium· asked at 3 companies
Delete Tail of Doubly Linked List
Problem
Given the head of a doubly linked list, delete the last node and return the head of the resulting list. If the list is empty return null; if it has one node the result is empty.
Input / Output
- Input: head of a DLL.
- Output: head after deleting the tail.
Examples
Example 1
Input: 1 <-> 2 <-> 3
Output: 1 <-> 2
Example 2
Input: 9
Output: empty list
Example 3
Input: 4 <-> 8
Output: 4
Constraints
0 <= number of nodes <= 10^5
Approach
- If
headisnull, returnnull. - If
head.nextisnull, the only node is the tail — returnnull. - Otherwise walk to the last node
tail(follownextuntilnextisnull). - Let
prev = tail.prev. Setprev.next = nullandtail.prev = null. - Return
head.
If the structure also maintains a tail pointer (common in production implementations), step 3 becomes O(1) and the whole deletion is constant time — worth mentioning as the reason doubly linked lists make good deques.
Complexity
- Time: O(n) to find the tail (O(1) with a stored tail pointer).
- Space: O(1)
Reference solution (Python)
def delete_tail(head):
if head is None or head.next is None:
return None
tail = head
while tail.next:
tail = tail.next
prev = tail.prev
prev.next = None
tail.prev = None
return head
Test cases
| Input | Expected |
|---|---|
1<->2<->3 | 1<->2 |
9 | None |
4<->8 | 4 |
| empty | None |