Skip to content

Commit e47d855

Browse files
committed
This is the implementation of the linked list
1 parent 9db3262 commit e47d855

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Node:
2+
__slots__ = ("value", "previous", "next")
3+
4+
def __init__(self, value):
5+
self.value = value
6+
self.previous = None
7+
self.next = None
8+
9+
10+
class LinkedList:
11+
def __init__(self):
12+
self.head = None
13+
self.tail = None
14+
15+
def push_head(self, value):
16+
node = Node(value)
17+
18+
if self.head is None:
19+
# empty list
20+
self.head = self.tail = node
21+
else:
22+
node.next = self.head
23+
self.head.previous = node
24+
self.head = node
25+
26+
return node #This is the handle
27+
28+
def pop_tail(self):
29+
if self.tail is None:
30+
raise IndexError("Pop from empty list")
31+
32+
node = self.tail
33+
34+
if node.previous is None:
35+
# One element
36+
self.head = self.tail = None
37+
else:
38+
self.tail = node.previous
39+
self.tail.next = None
40+
41+
return node.value
42+
43+
def remove(self, node):
44+
if node.previous:
45+
node.previous.next = node.next
46+
47+
else:
48+
# removing head
49+
self.head = node.next
50+
51+
if node.next:
52+
node.next.previous = node.previous
53+
else:
54+
# removing the tail
55+
self.tail = node.previous
56+
57+
# Clean up references
58+
59+
node.previous = None
60+
node.next = None

0 commit comments

Comments
 (0)