Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Sprint-2/implement_linked_list/linked_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from typing import Optional


class _Node:
def __init__(self, value):
self.value = value
self.next: Optional["_Node"] = None
self.prev: Optional["_Node"] = None
Comment on lines +4 to +8

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May I suggest exploring the use of __slots__ to reduce memory usage?



class LinkedList:
def __init__(self):
self.head = None
self.tail = None

def push_head(self, value):
new_node = _Node(value)

if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node

return new_node

def pop_tail(self):
if self.tail is None:
return None

value = self.tail.value

if self.head == self.tail:
self.head = None
self.tail = None
else:
self.tail = self.tail.prev
if self.tail:
self.tail.next = None
Comment on lines +35 to +41

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could also consider removing the tail by calling remove().


return value

def remove(self, node):
if node == self.head:
self.head = node.next
if self.head:
self.head.prev = None
else:
self.tail = None

elif node == self.tail:
self.tail = node.prev
if self.tail:
self.tail.next = None
else:
self.head = None

else:
node.prev.next = node.next
node.next.prev = node.prev
Comment on lines +45 to +62

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you look up why, in a doubly linked List implementation, assigning .next and .previous of the removed node to None a good practice?

No change required.

2 changes: 1 addition & 1 deletion Sprint-2/implement_linked_list/linked_list_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def test_remove_tail(self):
self.assertEqual(l.head, b)
self.assertEqual(l.tail, b)
self.assertIsNone(b.next)
self.assertIsNone(b.previous)
self.assertIsNone(b.prev)


if __name__ == "__main__":
Expand Down
Loading