Skip to content
Open
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
50 changes: 50 additions & 0 deletions Sprint-2/implement_linked_list/linked_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
class LinkedList:
def __init__(self):
self.head = None
self.tail = None

def push_head(self, element):
node = Node(element)
if self.head and self.tail:
Copy link

Choose a reason for hiding this comment

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

Is it necessary to check also self.tail?

node.next = self.head
self.head.previous = node
self.head = node
elif not self.head and not self.tail:
Copy link

Choose a reason for hiding this comment

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

This line could probably be simplified.

self.head = node
self.tail = node
return node

def pop_tail(self):
node = self.tail
if self.tail is not self.head:
self.tail = node.previous
node.previous.next = None
node.previous = None
else:
self.head = None
self.tail = None
return node.value

def remove(self, node):
if self.head != node and self.tail != node:
node.previous.next = node.next
node.next.previous = node.previous
node.previous, node.next = None, None
elif self.head == node and self.tail != node:
node.next.previous = None
self.head = node.next
node.previous, node.next = None, None
elif self.head != node and self.tail == node:
node.previous.next = None
self.tail = node.previous
node.previous, node.next = None, None
elif self.head == node and self.tail == node:
Comment on lines +29 to +41
Copy link

Choose a reason for hiding this comment

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

The conditions can be simplified (reduce the amount of checking needed) as:

   if self.head == node:
      if self.tail == node:
        # Case 1: head == node, tail == node
      else:
        # Case 2: head == node, tail != node
   else; 
     if self.tail == node:
        # Case 3: head != node, tail == node
     else:
        # Case 4: head != node, tail != node

Only two comparisons needed.

self.head = None
self.tail = None


class Node:
def __init__(self, value):
self.value = value
self.previous = None
self.next = None