1583. Drop the Last Sighting
A bird watcher logs species codes in a singly linked list, and the most recent sighting of one species turned out to be a mistake. Given head and a code v, remove only the last node whose value equals v, that is the one closest to the tail. Earlier nodes holding v must stay. If v does not occur, return the list as it is. Return the head of the resulting list, which is null if the removed node was the only one. Remember the previous node of the latest match while scanning once from the head: O(n) time and O(1) extra space.
Example 1
- Input:
- head = [4,2,4,9,4,1], v = 4
- Output:
- [4,2,4,9,1]
- Explanation:
The last 4 sits at position 5, so only that node is removed: 4, 2, 4, 9, 1.
Example 2
- Input:
- head = [1,2,3], v = 7
- Output:
- [1,2,3]
- Explanation:
The value 7 never appears, so the list is unchanged.
Example 3
- Input:
- head = [6,6,6], v = 6
- Output:
- [6,6]
- Explanation:
Only the last of the three 6 nodes is removed, leaving 6, 6.
Constraints
0 ≤ length ≤ 1000
val and v fit in a 32-bit signed integer
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)