Linked Lists
Iterative Solution:
def reverse_linked_list_in_place(lst):
"""Given linked list, reverse the nodes in this linked list in place."""
# START SOLUTION
prev = None
curr = lst.head
while curr is not None:
next = curr.next
curr.next = prev
prev = curr
curr = next
lst.head = prev
Alternative Recursive Solution:
def reverse_linked_list_in_place_rec(lst):
"""Given linked list, RECUSIVELY reverse the nodes
in this linked list in place."""
curr = lst.head
prev = None
def _rec_reverse(curr, prev):
#base case
if not curr:
return prev
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return _rec_reverse(curr, prev)
lst.head = _rec_reverse(curr, prev)