-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_list.py
91 lines (73 loc) · 1.75 KB
/
doubly_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
82
83
84
85
86
87
88
89
90
91
class Node(object):
def __init__(self, data):
self.data = data
self.parent = None
self.prev = None
self.next = None
self.children = DoublyList()
self.mark = False
self.active = False
class DoublyList(object):
def __init__(self):
self.head = None
self.tail = None
self.len = 0
def append(self, data):
new_node = Node(data)
return self.append_node(new_node)
def append_node(self, node):
self.len += 1
if self.head == None:
self.head = self.tail = node
else:
node.prev = self.tail
node.next = None
self.tail.next = node
self.tail = self.tail.next
return node
def remove(self, node):
if node == self.head:
return self.pop()
else:
self.len -= 1
node.prev.next = node.next
if node.next != None:
node.next.prev = node.prev
if self.tail == node:
self.tail = node.prev
node.next = None
node.prev = None
return node
def pop(self):
self.len -= 1
curr = self.head
if self.len == 0:
self.head = None
self.tail = None
else:
self.head = curr.next
self.head.prev = None
curr.next = None
return curr
def get_items(self):
if self.len == 0:
return []
items = []
curr = self.head
items.append(curr.data)
while curr.next != None:
curr = curr.next
items.append(curr.data)
return items
def get_nodes(self):
if self.len == 0:
return []
nodes = []
curr = self.head
nodes.append(curr)
while curr.next != None:
curr = curr.next
nodes.append(curr)
return nodes
def __len__(self):
return self.len