Remove Duplicates from Sorted List — linked-list walk
Three pointers: prev, cur, next. Flip one edge per step. Built for LeetCode 83. Remove Duplicates from Sorted List.
You only ever need the next node saved before you rewire cur.next = prev. Walk until cur is nil; prev is the new head.
Algorithm
prev = null,cur = head.- Save
next, flip the edge, slideprevandcurforward. - Return
prev.
- Time
- O(n)
- Space
- O(1)
class Solution: def removeDuplicatesFromSortedList(self, head: list[int]) -> list[int]: prev: list[int] = [] cur = head while cur: nxt = cur[1:] prev = [cur[0], *prev] cur = nxt return prev