Linked Lists
Loading
Loading
Linked Lists
The pointer discipline: save before you overwrite, and use a dummy head.
By the end of this chapter
1 → 2 → 3 → nullprev=null cur=1save 2, point 1 at nullprev=1 cur=2save 3, point 2 at 1prev=2 cur=3save null, point 3 at 2cur=nullprev is the new head3 → 2 → 1 → nulldef reverse(head): prev = None node = head while node is not None: nxt = node.next # save BEFORE overwriting node.next = prev prev = node node = nxt return prev # not head: head is now the tailOperations that might affect the first node otherwise need a branch for it. A throwaway node in front removes that asymmetry entirely.
def remove_value(head, target): dummy = ListNode(0, head) # now nothing is special about the first node prev = dummy while prev.next is not None: if prev.next.val == target: prev.next = prev.next.next # unlink else: prev = prev.next return dummy.nextQuick quiz
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for:
Before moving on: take the quiz above, and try 3 practice problems.