Delete Tail of Doubly Linked List
Pattern: Doubly and circular lists
Walk to the tail. Its prev node becomes the new end, so set that node's next to null. A list of one node becomes empty.
The problem
Given the head of a doubly linked list, delete its last node and return the head. A list with one node becomes empty.
For example, 1 ⇄ 2 ⇄ 3 becomes 1 ⇄ 2, and 7 becomes empty.
The function name deleteTail matches the takeUforward practice page. Use the link above for the exact statement and
limits. In this guide's code the node type is DNode.
Think first
- In a singly linked list you needed the second-to-last node. How do you reach it here?
- Which pointers must change?
- What about a single node?
Hints
Brute force, and why it fails
Rebuilding the list without the last value is O(n) with new nodes. Walking to the tail and cutting one link is O(n) with no new nodes, and O(1) if a tail pointer were kept.
The key insight
The prev pointer gives the node before for free, so the tail can be removed from itself.
Dry run
The list is 1 ⇄ 2 ⇄ 3. Walk to the tail, 3.
The plan
if head is null or head.next is null: return null
tail = head
while tail.next is not null: tail = tail.next
tail.prev.next = null
tail.prev = null
return head
Complexity
- Time
O(n)- Space
O(1)
One walk to the tail.
Edge cases
- One node: empty.
- Two nodes: only the head is left.
- Empty list: empty.
I've built my logic, show the code
Java
class Solution {
public DNode deleteTail(DNode head) {
if (head == null || head.next == null) return null; // zero or one node: nothing is left
DNode tail = head;
while (tail.next != null) tail = tail.next;
tail.prev.next = null; // the node before the tail is the new end
tail.prev = null;
return head;
}
}C++
class Solution {
public:
DNode* deleteTail(DNode* head) {
if (head == NULL || head->next == NULL) return NULL; // zero or one node: nothing is left
DNode* tail = head;
while (tail->next != NULL) tail = tail->next;
tail->prev->next = NULL; // the node before the tail is the new end
tail->prev = NULL;
return head;
}
};Python
from lib import DNode
class Solution:
def deleteTail(self, head: DNode) -> DNode:
if head is None or head.next is None:
return None # zero or one node: nothing is left
tail = head
while tail.next is not None:
tail = tail.next
tail.prev.next = None # the node before the tail is the new end
tail.prev = None
return headCommon mistakes
- Forgetting the one-node case, where
tail.previs null. - Returning the tail instead of the head.
- Leaving
nexton the second-to-last node pointing at the deleted tail.