-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_linked_list.py
81 lines (70 loc) · 1.96 KB
/
doubly_linked_list.py
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
75
76
77
78
79
80
81
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def isEmpty(self):
if self.head is None:
return True
else:
return False
def prepend(self, item):
node = Node(item)
if self.isEmpty():
self.head = self.tail = node
else:
current = self.head
self.head = node
node.prev = None
node.next = current
self.length += 1
def append(self, item):
node = Node(item)
if self.isEmpty():
self.head = self.tail = node
else:
current = self.head
while current.next:
current = current.next
last = current
current.next = node
self.tail = node
node.prev = last
self.length += 1
def popFirst(self):
if self.head:
current = self.head
self.head = current.next
current.next.prev = None
self.length -= 1
def pop(self):
if self.head:
second_last = self.tail.prev
self.tail = second_last
self.tail.next = None
self.length -= 1
def toArray(self):
array = []
if self.head:
current = self.head
while current:
array.append(current.data)
current = current.next
return array
def size(self):
return self.length
if __name__ == "__main__":
doublyLinkedList = DoublyLinkedList()
doublyLinkedList.prepend(100)
doublyLinkedList.append("A")
doublyLinkedList.popFirst()
doublyLinkedList.prepend("500")
doublyLinkedList.append(-10)
doublyLinkedList.pop()
print(doublyLinkedList.toArray())
print(doublyLinkedList.isEmpty())