Advertisement
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)
- return
- def to_list(self):
- mylist = []
- if self.head is None:
- return
- node = self.head
- while node:
- mylist.append(node.value)
- node = node.next
- return mylist
- # Test your method here
- linked_list = LinkedList()
- linked_list.append(3)
- linked_list.append(2)
- linked_list.append(-1)
- linked_list.append(0.2)
- print ("Pass" if (linked_list.to_list() == [3, 2, -1, 0.2]) else "Fail")
- class DoubleNode:
- def __init__(self, value):
- self.value = value
- self.next = None
- self.previous = None
- class DoublyLinkedList:
- def __init__(self):
- self.head = None
- self.tail = None
- def append(self, data):
- if self.head is None:
- self.head = DoubleNode(data)
- self.tail = self.head
- return
- else:
- newnode = DoubleNode(data)
- self.tail.next = newnode
- newnode.previous = self.tail
- self.tail = newnode
- return
- # Test your class here
- linked_list = DoublyLinkedList()
- linked_list.append(1)
- linked_list.append(-2)
- linked_list.append(4)
- print("Going forward through the list, should print 1, -2, 4")
- node = linked_list.head
- while node:
- print(node.value)
- node = node.next
- print("\nGoing backward through the list, should print 4, -2, 1")
- node = linked_list.tail
- while node:
- print(node.value)
- node = node.previous
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement