fork(1) download
  1. #!/usr/bin/env python
  2. """Reverse linked list."""
  3.  
  4.  
  5. class Node:
  6. """Linked list is either None or a value and a link to the next list."""
  7.  
  8. def __init__(self, data, next=None):
  9. self.data = data
  10. self.next = next
  11.  
  12.  
  13. head = Node(1, Node(2, Node(3, Node(4))))
  14.  
  15.  
  16. def print_list(head, end='\n'):
  17. while head:
  18. print(head.data, end=' -> ' if head.next else '')
  19. head = head.next
  20. print(end=end)
  21.  
  22.  
  23. print_list(head)
  24.  
  25.  
  26. def reverse_list(head, tail=None):
  27. while head:
  28. head.next, tail, head = tail, head, head.next
  29. return tail
  30.  
  31.  
  32. print_list(reverse_list(head))
  33.  
Success #stdin #stdout 0.02s 28520KB
stdin
Standard input is empty
stdout
1 -> 2 -> 3 -> 4
4 -> 3 -> 2 -> 1