Skip to content

Commit f45f5ca

Browse files
committed
LinkedList implementation with double linked list.
1 parent e718fb4 commit f45f5ca

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# `push_head` should add an element to the start of the list. It should return something that can be passed to
2+
# `remove` to remove that element in the future.
3+
# `pop_tail` should remove an element from the end of the list.
4+
# `remove` takes a handle from `push_head`, and removes that element from the list.
5+
6+
class LinkedList:
7+
class _Node: # to have O(1) must be implemented double linked list to access previous
8+
__slots__ = ("value", "prev", "next")
9+
10+
def __init__(self, value):
11+
self.value = value
12+
self.prev = None
13+
self.next = None
14+
15+
def __init__(self):
16+
self.head = None
17+
self.tail = None
18+
19+
def push_head(self, value):
20+
node = self._Node(value)
21+
22+
node.next = self.head
23+
if self.head:
24+
self.head.prev = node
25+
else:
26+
# when list gets empty, tail also becomes this node
27+
self.tail = node
28+
29+
self.head = node
30+
return node # handling
31+
32+
def pop_tail(self):
33+
if not self.tail:
34+
raise IndexError("pop from empty list")
35+
36+
node = self.tail
37+
value = node.value
38+
39+
self.tail = node.prev
40+
if self.tail:
41+
self.tail.next = None
42+
else:
43+
# when the list gets empty
44+
self.head = None
45+
46+
return value
47+
48+
def remove(self, node):
49+
if node.prev:
50+
node.prev.next = node.next
51+
else:
52+
# removes head
53+
self.head = node.next
54+
55+
if node.next:
56+
node.next.prev = node.prev
57+
else:
58+
# removes tail
59+
self.tail = node.prev

0 commit comments

Comments
 (0)