Worked Linked List 1: Reverse Linked List
Given the head of a singly linked list, reverse the list and return the new head.
Hidden answer: invariant, common mistake, and Python solution
Invariant: prev is the fully reversed prefix and
cur is the first node in the unreversed suffix. The
common mistake is overwriting cur.next before saving
the original next node.
def reverse_list(head):
prev = None
cur = head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev