Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. class Node:
  2. def __init__(self, value):
  3. self.value = value
  4. self.next = None
  5.  
  6.  
  7. class LinkedList():
  8. def __init__(self):
  9. self.head = None
  10.  
  11. def append(self, value):
  12. if self.head is None:
  13. self.head = Node(value)
  14. return
  15. node = self.head
  16. while node.next:
  17. node = node.next
  18. node.next = Node(value)
  19. return
  20.  
  21. def to_list(self):
  22. mylist = []
  23. if self.head is None:
  24. return
  25. node = self.head
  26. while node:
  27. mylist.append(node.value)
  28. node = node.next
  29. return mylist
  30.  
  31.  
  32. # Test your method here
  33. linked_list = LinkedList()
  34. linked_list.append(3)
  35. linked_list.append(2)
  36. linked_list.append(-1)
  37. linked_list.append(0.2)
  38.  
  39. print ("Pass" if (linked_list.to_list() == [3, 2, -1, 0.2]) else "Fail")
  40.  
  41.  
  42. class DoubleNode:
  43. def __init__(self, value):
  44. self.value = value
  45. self.next = None
  46. self.previous = None
  47.  
  48.  
  49. class DoublyLinkedList:
  50. def __init__(self):
  51. self.head = None
  52. self.tail = None
  53.  
  54. def append(self, data):
  55. if self.head is None:
  56. self.head = DoubleNode(data)
  57. self.tail = self.head
  58. return
  59. else:
  60. newnode = DoubleNode(data)
  61. self.tail.next = newnode
  62. newnode.previous = self.tail
  63. self.tail = newnode
  64. return
  65.  
  66.  
  67. # Test your class here
  68.  
  69. linked_list = DoublyLinkedList()
  70. linked_list.append(1)
  71. linked_list.append(-2)
  72. linked_list.append(4)
  73.  
  74. print("Going forward through the list, should print 1, -2, 4")
  75. node = linked_list.head
  76. while node:
  77. print(node.value)
  78. node = node.next
  79.  
  80. print("\nGoing backward through the list, should print 4, -2, 1")
  81. node = linked_list.tail
  82. while node:
  83. print(node.value)
  84. node = node.previous
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement