Skip to content
Open
Changes from 1 commit
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
64 changes: 64 additions & 0 deletions Sprint-2/implement_linked_list/linked_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
class Node:
def __init__(self, data):
self.data = data
self.previous = None
self.next = None

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

def push_head(self, data):
new_head_node = Node(data)
if self.head is not None:
new_head_node.next = self.head
self.head.previous = new_head_node

self.head = new_head_node
if self.tail is None:
self.tail = new_head_node

return new_head_node



def pop_tail(self):
if self.tail is not None:
tail_node = self.tail
previous = self.tail.previous
self.tail = previous
if self.tail is not None:
self.tail.next = None
else:
self.head = None
else:
raise IndexError("Unable to remove from empty linked list")

Comment thread
cjyuan marked this conversation as resolved.
Outdated
return tail_node.data
Comment on lines +30 to +32
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  • Is line 40 needed?

  • You could replace the code on lines 30-42 by 3 lines of code if you delegate the node-removing task to remove().

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

yeah line 40 is definitely useless since a tail node's next should already be None. Not so intelligent of me!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Regarding "You could replace the code on lines 30-42 by 3 lines of code if you delegate the node-removing task to remove()", I just updated my logic inside pop_tail function accordingly.




def remove(self, node):
if node.previous is not None:
node.previous.next = node.next
else:
self.head = node.next

if node.next is not None:
node.next.previous = node.previous
else:
self.tail = node.previous