1.Reverse a linked list
BeginnerBuild the list 1 → 2 → 3 → 4 from Node objects, reverse it in place, and print the values of the reversed list.
Show hint
Walk the list with prev and current, saving current.next before pointing it back at prev.
Show solution
class Node:
def __init__(self, value, next=None):
self.value, self.next = value, next
def reverse(head):
prev = None
while head:
nxt = head.next
head.next = prev
prev, head = head, nxt
return prev
head = Node(1, Node(2, Node(3, Node(4))))
node = reverse(head)
values = []
while node:
values.append(node.value)
node = node.next
print(values)[4, 3, 2, 1]