Skip to content

Commit 8e95bf5

Browse files
committed
implement linked list
1 parent 134e683 commit 8e95bf5

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Node():
2+
def __init__(self, value) -> None:
3+
self.value = value
4+
self.next = None
5+
self.previous = None
6+
7+
class LinkedList():
8+
def __init__(self) -> None:
9+
self.head = None
10+
self.tail = None
11+
12+
# [1, 2 ] - 4
13+
def push_head(self, value): # add element to the start of list.
14+
handle = Node(value)
15+
handle.next = self.head
16+
17+
if self.head:
18+
self.head.previous = handle
19+
else:
20+
self.tail = handle
21+
22+
self.head = handle
23+
return handle
24+
25+
# [4, 1, 2]
26+
def pop_tail(self): # remove element from end of list
27+
if not self.tail:
28+
return None
29+
30+
value = self.tail.value # 2
31+
new_tail = self.tail.previous # 1
32+
33+
if new_tail:
34+
new_tail.next = None
35+
else:
36+
self.head = None
37+
38+
self.tail = new_tail
39+
return value
40+
41+
# [4, 1, 2] - 1
42+
def remove(self, handle): # takes handle from 'push_head' + remove it
43+
if handle.previous: #4
44+
handle.previous.next = handle.next
45+
else:
46+
self.head = None
47+
48+
if handle.next: #2
49+
handle.next.previous = handle.previous
50+
else:
51+
self.tail = handle.previous
52+
53+
handle.next = None
54+
handle.previous = None

0 commit comments

Comments
 (0)