Skip to content

Commit 07c8b28

Browse files
committed
Implement doubly linked list: O(1) operations for head and tail
1 parent 134e683 commit 07c8b28

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
class Node:
2+
# This class is for the Node (the item).
3+
# It keeps the value and pointers to next and previous.
4+
def __init__(self, value):
5+
self.value = value
6+
self.next = None # Pointer to next node
7+
self.previous = None # Pointer to previous node
8+
9+
10+
class LinkedList:
11+
# This class controls the list.
12+
# It tracks head and tail. operations are O(1).
13+
def __init__(self):
14+
self.head = None
15+
self.tail = None
16+
17+
def push_head(self, value):
18+
# Create a new node with the value
19+
new_node = Node(value)
20+
21+
# If list is empty, head and tail is this new node
22+
if self.head is None:
23+
self.head = new_node
24+
self.tail = new_node
25+
else:
26+
# If list not empty, put new node at start
27+
new_node.next = self.head # Link new node to old head
28+
self.head.previous = new_node # Link old head back to new node
29+
self.head = new_node # Update head pointer
30+
31+
return new_node
32+
33+
def pop_tail(self):
34+
# Remove the last item (tail)
35+
if self.tail is None:
36+
return None
37+
38+
value_to_return = self.tail.value
39+
40+
# Check if only 1 item in list
41+
if self.head == self.tail:
42+
self.head = None
43+
self.tail = None
44+
else:
45+
# More than 1 item. Move tail pointer back.
46+
self.tail = self.tail.previous
47+
self.tail.next = None # Cut the link to the old tail
48+
49+
return value_to_return
50+
51+
def remove(self, node):
52+
# Remove a specific node from the list.
53+
# We just assume node is definitely in the list.
54+
55+
# If removing the Head node
56+
if node == self.head:
57+
self.head = node.next
58+
if self.head:
59+
self.head.previous = None
60+
else:
61+
self.tail = None # List became empty
62+
63+
# If removing the Tail node
64+
elif node == self.tail:
65+
self.tail = node.previous
66+
if self.tail:
67+
self.tail.next = None
68+
else:
69+
self.head = None
70+
71+
# If removing a node in the middle
72+
else:
73+
# Link previous node to the next node
74+
node.previous.next = node.next
75+
# Link next node to the previous node
76+
node.next.previous = node.previous

0 commit comments

Comments
 (0)