-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoubly_linked_list.py
More file actions
74 lines (63 loc) · 1.95 KB
/
Copy pathdoubly_linked_list.py
File metadata and controls
74 lines (63 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Node:
def __init__(self, value, next=None, prev=None) -> None:
self.value = value
self.next = next
self.prev = prev
def __str__(self) -> str:
return str(self.value)
class DoublyLinkedList:
def __init__(self) -> None:
self.head = None
self.tail = None
def __str__(self) -> str:
return u"\u2022" + " <- (head) "+' <--> '.join([str(node) for node in self])+" (tail) -> "+ u"\u2022"
def __len__(self):
count = 0
node = self.head
while node:
count += 1
node = node.next
return count
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
def add_at_head(self, value):
if self.is_empty():
self.head = self.tail = Node(value)
else:
node = Node(value=value, next=self.head, prev=None)
self.head.prev = node
self.head = node
def add_at_tail(self, value):
if self.is_empty():
self.head = self.tail = Node(value)
else:
node = Node(value=value, next = None, prev=self.tail)
self.tail.next = node
self.tail = node
def is_empty(self):
return self.__len__() == 0
def main():
try:
ll = DoublyLinkedList()
print("Empty?: ", ll.is_empty())
while True:
print("\nEnter a number:", end=" ")
new_node = input()
ll.add_at_head(int(new_node))
print("Linked List: ",ll)
print("Length: ", len(ll))
except (ValueError, KeyboardInterrupt):
ll.add_at_tail(-1)
ll.add_at_tail(-2)
ll.add_at_tail(-3)
ll.add_at_tail(-4)
print("Final Linked list: ", ll)
print("Empty?: ", ll.is_empty())
print("Total Items", len(ll))
print("Wrong input, Exiting now!!!")
exit(0)
if __name__=="__main__":
main()