Skip to content

Commit 84c810f

Browse files
committed
linked list
1 parent f45f5ca commit 84c810f

File tree

1 file changed

+34
-34
lines changed

1 file changed

+34
-34
lines changed

Sprint-2/implement_linked_list/linked_list.py

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -3,57 +3,57 @@
33
# `pop_tail` should remove an element from the end of the list.
44
# `remove` takes a handle from `push_head`, and removes that element from the list.
55

6-
class LinkedList:
7-
class _Node: # to have O(1) must be implemented double linked list to access previous
8-
__slots__ = ("value", "prev", "next")
6+
class Node:
7+
def __init__(self, value):
8+
self.value = value
9+
self.prev = None
10+
self.next = None
911

10-
def __init__(self, value):
11-
self.value = value
12-
self.prev = None
13-
self.next = None
1412

13+
class LinkedList:
1514
def __init__(self):
16-
self.head = None
17-
self.tail = None
15+
self.head = None
16+
self.tail = None
1817

18+
# adding a new value in the front of the list
1919
def push_head(self, value):
20-
node = self._Node(value)
20+
node = Node(value)
2121

22-
node.next = self.head
23-
if self.head:
24-
self.head.prev = node
22+
if self.head is None: # if list is empty head and tail becomes this node.
23+
self.head = node
24+
self.tail = node
2525
else:
26-
# when list gets empty, tail also becomes this node
27-
self.tail = node
26+
node.next = self.head
27+
self.head.prev = node
28+
self.head = node
2829

29-
self.head = node
30-
return node # handling
30+
return node # returns the node so we can remove it later
3131

32+
# removing last element
3233
def pop_tail(self):
33-
if not self.tail:
34-
raise IndexError("pop from empty list")
34+
if self.tail is None:
35+
raise Exception("List is empty")
3536

36-
node = self.tail
37-
value = node.value
37+
value = self.tail.value # value to return
3838

39-
self.tail = node.prev
40-
if self.tail:
41-
self.tail.next = None
42-
else:
43-
# when the list gets empty
39+
if self.head == self.tail: # if only one element
4440
self.head = None
41+
self.tail = None
42+
else:
43+
self.tail = self.tail.prev # move tail back
44+
self.tail.next = None # remove old tail connection
4545

4646
return value
4747

48+
# removes a specific node
4849
def remove(self, node):
49-
if node.prev:
50-
node.prev.next = node.next
51-
else:
52-
# removes head
53-
self.head = node.next
5450

55-
if node.next:
56-
node.next.prev = node.prev
51+
if node.prev is None: # if removing head
52+
self.head = node.next
5753
else:
58-
# removes tail
54+
node.prev.next = node.next # connect previous to next
55+
56+
if node.next is None: # if removing tail
5957
self.tail = node.prev
58+
else:
59+
node.next.prev = node.prev # connect next to previous

0 commit comments

Comments
 (0)