Delete the Last Node of a Linked List
Implement deleteAtEnd
Given the
head of a singly linked list, delete the last node and return the head of the resulting list. If the list is empty or has just one node, the result is an empty list.
Unlike deleting the first node, this one still requires a walk from head — a singly linked list keeps no pointer to its own tail, so the second-to-last node has to be found by checking one node ahead at each step (curr.next.next == null). Once found, dropping the last node is a single pointer write.
Example 1:
Input: head = [3,8,5,1]
Output: [3,8,5]
Example 2:
Input: head = [9]
Output: []
Example 3:
Input: head = []
Output: []
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 10⁴ - ●
-10⁹ ≤ node value ≤ 10⁹ - ●
Handle the empty list and the single-node list — both must return an empty list
head =
[3, 8, 5, 1]