Deletion of the tail of Linked List
Pattern: Traversal and dummy nodes
Walk to the second-to-last node and set its next to null. A list of one node becomes empty.
The problem
Given the head of a singly linked list, delete its last node and return the head. If the list has one node, the result
is empty. For example, 1 → 2 → 3 becomes 1 → 2, and 7 becomes an empty list.
The function name deleteTail matches the takeUforward practice page. Use the link above for the exact statement and
limits.
Think first
- Which node's pointer must change to remove the tail?
- How do you stop at that node instead of the tail itself?
- What happens with only one node?
Hints
Brute force, and why it fails
Copy the values to an array, drop the last one and rebuild the list: O(n) time and O(n) memory. One walk and one pointer change need O(1) memory.
The key insight
In a singly linked list, a node can only be removed from the node before it. For the tail, that means walking to the second-to-last node.
Dry run
The list is 1 → 2 → 3. The tail is 3, so the node before it, 2, must become the end.
The plan
if head is null or head.next is null: return null
cur = head
while cur.next.next is not null: cur = cur.next
cur.next = null
return head
Complexity
- Time
O(n)- Space
O(1)
One walk to the end.
Edge cases
- One node: the result is empty.
- Two nodes: only the head is left.
- Empty list: still empty.
I've built my logic, show the code
Java
class Solution {
public ListNode deleteTail(ListNode head) {
if (head == null || head.next == null) return null; // zero or one node: nothing is left
ListNode cur = head;
while (cur.next.next != null) cur = cur.next; // stop at the second-to-last node
cur.next = null; // cut the last node off
return head;
}
}C++
class Solution {
public:
ListNode* deleteTail(ListNode* head) {
if (head == NULL || head->next == NULL) return NULL; // zero or one node: nothing is left
ListNode* cur = head;
while (cur->next->next != NULL) cur = cur->next; // stop at the second-to-last node
cur->next = NULL; // cut the last node off
return head;
}
};Python
from lib import ListNode
class Solution:
def deleteTail(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return None # zero or one node: nothing is left
cur = head
while cur.next.next is not None: # stop at the second-to-last node
cur = cur.next
cur.next = None # cut the last node off
return headCommon mistakes
- Walking to the tail itself, where there is no way back to the node before it.
- Reading
head.next.nextwhen the list has one node. - Returning the deleted node instead of the head.