diff --git a/Sprint-2/implement_linked_list/linked_list.py b/Sprint-2/implement_linked_list/linked_list.py index e69de29..74fb45f 100644 --- a/Sprint-2/implement_linked_list/linked_list.py +++ b/Sprint-2/implement_linked_list/linked_list.py @@ -0,0 +1,53 @@ +class Node: #A node in a doubly linked list + def __init__(self, value): #Initialize a new node with the given value and no next or previous nodes + self.value = value + self.previous = None + self.next = None + + +class LinkedList: # A doubly linked list data structure + def __init__(self): # Initialize an empty linked list with no head node + self.head = None + self.tail = None + + def push_head(self, value): # Add a new node with the given value to the head of the list + new_node = Node(value) # Create a new node with the given value + + new_node.next = self.head # Set the new node's next pointer to the current head of the list + if self.head: # If the list is not empty, set the current head's previous pointer to the new node + self.head.previous = new_node + else: + self.tail = new_node + + self.head = new_node # Update the head of the list to be the new node + return new_node # Return node for O(1) removal later + + def remove(self, node): # Remove the given node from the list + if node.previous: + node.previous.next = node.next + else: + # Removing head + self.head = node.next + + if node.next: + node.next.previous = node.previous + else: + # Removing tail + self.tail = node.previous + + # Clean up references + node.previous = None + node.next = None + + def pop_tail(self): + if not self.tail: + return None + + old_tail = self.tail + value = old_tail.value + + self.remove(old_tail) # handles pointer updates + cleanup + + return value + + diff --git a/Sprint-2/implement_linked_list/linked_list_test.py b/Sprint-2/implement_linked_list/linked_list_test.py index d59d9c5..68d70b6 100644 --- a/Sprint-2/implement_linked_list/linked_list_test.py +++ b/Sprint-2/implement_linked_list/linked_list_test.py @@ -1,5 +1,4 @@ import unittest - from linked_list import LinkedList class LinkedListTest(unittest.TestCase):