Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, value):
- self.value = value
- self.next = None
- class LinkedList:
- def __init__(self):
- self.head = None
- def append(self, value):
- if self.head is None:
- self.head = Node(value)
- return
- node = self.head
- while node.next:
- node = node.next
- node.next = Node(value)
- def reverse(self):
- if self.head is None:
- return
- curr = self.head
- prev = None
- while curr:
- next = curr.next
- curr.next = prev
- prev = curr
- curr = next
- self.head = prev
- print self.head.value
- print self.head.next.value
- print self.head.next.next.value
- def __iter__(self):
- node = self.head
- while node:
- yield node.value
- node = node.next
- def __repr__(self):
- return str([v for v in self])
- def reverse(linked_list):
- new_list = LinkedList()
- if linked_list is None:
- return new_list
- node = linked_list.head
- new_list.head = node
- while node:
- old_head = new_list.head
- curr = node
- node = node.next
- new_list.head = curr
- new_list.head.next = old_head
- return new_list
- if __name__ == "__main__":
- a = LinkedList()
- b = [1,2,3,4,5]
- for item in b:
- a.append(item)
- print(a)
- c = a.reverse()
- print(a)
- print(c)
Advertisement
Add Comment
Please, Sign In to add comment