How To Reverse a LinkedList
Imagine we have the following data structure for a node in a Linked List.
1class LinkedList:2 def __init__(self, value):3 self.value = value4 self.next = None5
6
7# return the head of the new linked list8def reverseLinkedList(head):9 # go!We start out with a linked list like this
None 0 -> 1 -> 2 -> 3 -> 4 -> 5prev A BThe variable head points at 0.
There are a few constraints when solving this problem
- Your solution should absolutely be
O(n) - Use as few variables as possible - management of the pointers is what makes this problem challenging
Walking through each iteration helped me.
# after 1 iterationNone <- 0 1 -> 2 -> 3 -> 4 -> 5 prev A BWe set A.next to prev, then iterate forward. The variable B really just exists so we can iterate forward once we point A.next elsewhere.
# after 2 iterationsNone <- 0 <- 1 2 -> 3 -> 4 -> 5 prev A B
# after 3 iterationsNone <- 0 <- 1 <- 2 3 -> 4 -> 5 prev A B
# after 4 iterationsNone <- 0 <- 1 <- 2 <- 3 4 -> 5 prev A B
# after 5 iterationsNone <- 0 <- 1 <- 2 <- 3 <- 4 5 prev A B
# after 6 iterationsNone <- 0 <- 1 <- 2 <- 3 <- 4 <- 5 None None prev A BNote that prev now points at the new head.
Here’s the final solution.
1class LinkedList:2 def __init__(self, value):3 self.value = value4 self.next = None5
6
7def reverseLinkedList(head):8 prev = None9 a = head10 b = a.next11
12 while a is not None:13 a.next = prev14
15 prev = a16 a = b17 b = b.next if b is not None else None18
19 return prevYou can get rid of the if b is not None else None section if you rearrange the order in which you set everything (you set b = a.next before you do a.next = prev, but honestly I find that harder to reason about.
This solution has O(n) time complexity and O(1) space complexity.