Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. class Node:
  2. def __init__(self, value):
  3. self.value = value
  4. self.next = None
  5.  
  6. class LinkedList:
  7. def __init__(self):
  8. self.head = None
  9. def append(self, value):
  10. if self.head is None:
  11. self.head = Node(value)
  12. return
  13.  
  14. node = self.head
  15. while node.next:
  16. node = node.next
  17.  
  18. node.next = Node(value)
  19.  
  20. def reverse(self):
  21. if self.head is None:
  22. return
  23. curr = self.head
  24. prev = None
  25. while curr:
  26. next = curr.next
  27. curr.next = prev
  28. prev = curr
  29. curr = next
  30. self.head = prev
  31. print self.head.value
  32. print self.head.next.value
  33. print self.head.next.next.value
  34. def __iter__(self):
  35. node = self.head
  36. while node:
  37. yield node.value
  38. node = node.next
  39.  
  40. def __repr__(self):
  41. return str([v for v in self])
  42.  
  43. def reverse(linked_list):
  44. new_list = LinkedList()
  45. if linked_list is None:
  46. return new_list
  47. node = linked_list.head
  48. new_list.head = node
  49. while node:
  50. old_head = new_list.head
  51. curr = node
  52. node = node.next
  53. new_list.head = curr
  54. new_list.head.next = old_head
  55.  
  56. return new_list
  57.  
  58. if __name__ == "__main__":
  59. a = LinkedList()
  60. b = [1,2,3,4,5]
  61. for item in b:
  62. a.append(item)
  63. print(a)
  64. c = a.reverse()
  65. print(a)
  66. print(c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement