-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.py
95 lines (63 loc) · 2.07 KB
/
DoublyLinkedList.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
92
93
94
95
from Node import Node
class DoublyLinkedList:
def __init__(self):
self.head_node = None
self.tail_node = None
def add_to_head(self, new_value):
new_head = Node(new_value)
current_head = self.head_node
if current_head != None:
current_head.set_prev_node(new_head)
new_head.set_next_node(current_head)
self.head_node = new_head
if self.tail_node == None:
self.tail_node = new_head
def add_to_tail(self, new_value):
new_tail = Node(new_value)
current_tail = self.tail_node
if current_tail != None:
current_tail.set_next_node(new_tail)
new_tail.set_prev_node(current_tail)
self.tail_node = new_tail
if self.head_node == None:
self.head_node = new_tail
def remove_head(self):
removed_head = self.head_node
if removed_head == None:
return None
self.head_node = removed_head.get_next_node()
if self.head_node != None:
self.head_node.set_prev_node(None)
if removed_head == self.tail_node:
self.remove_tail()
return removed_head.get_value()
def remove_tail(self):
removed_tail = self.tail_node
if removed_tail == None:
return None
self.tail_node = removed_tail.get_prev_node()
if self.tail_node != None:
self.tail_node.set_next_node(None)
if removed_tail == self.head_node:
self.remove_head()
return removed_tail.get_value()
def remove_by_value(self, value_to_remove):
node_to_remove = None
current_node = self.head_node
while current_node != None:
if current_node.get_value() == value_to_remove:
node_to_remove = current_node
break
current_node = current_node.get_next_node()
if node_to_remove == None:
return None
if node_to_remove == self.head_node:
self.remove_head()
elif node_to_remove == self.tail_node:
self.remove_tail()
else:
next_node = node_to_remove.get_next_node()
prev_node = node_to_remove.get_prev_node()
next_node.set_prev_node(prev_node)
prev_node.set_next_node(next_node)
return node_to_remove