From a45e1e95850bd18b45ebf88f04c4410241d336ad Mon Sep 17 00:00:00 2001 From: Brendan Chen Date: Wed, 25 Feb 2026 15:15:35 -0800 Subject: [PATCH] Add linked list solution --- .../2026.02.28/linked_list_solution.py | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 shared/notes-and-examples/2026.02.28/linked_list_solution.py diff --git a/shared/notes-and-examples/2026.02.28/linked_list_solution.py b/shared/notes-and-examples/2026.02.28/linked_list_solution.py new file mode 100644 index 0000000..52f885f --- /dev/null +++ b/shared/notes-and-examples/2026.02.28/linked_list_solution.py @@ -0,0 +1,71 @@ +# Solution to 2026.01.28 homework + +class Node: + prev_node: "Node | None" = None + next_node: "Node | None" = None + + def __init__(self, value) -> None: + self.value = value + +class LinkedList: + head: "Node | None" = None + tail: "Node | None" = None + + def append(self, thing): + if self.head==None: + self.head=Node(value=thing) + self.tail=self.head + return + + if self.tail is not None: + self.tail.next_node=Node(value=thing) + if self.tail.next_node is not None: + self.tail.next_node.prev_node = self.tail + self.tail=self.tail.next_node + + def prepend(self, thing): + previous_head = self.head + self.head = Node(value=thing) + self.head.next_node = previous_head + + if previous_head is not None: + previous_head.prev_node = self.head + + def insert(self, thing, index): + current_node = self.head + if current_node is None: + self.append(thing) + return + + if index == 0: + self.prepend(thing) + return + + for _ in range(1, index): + if current_node is not None: + current_node = current_node.next_node + if current_node is None: + raise IndexError + + prev_next = current_node.next_node + current_node.next_node = Node(thing) + current_node.next_node.prev_node = current_node + current_node.next_node.next_node = prev_next + + + def print_list(self): + current_node = self.head + while current_node is not None: + print(current_node.value) + current_node = current_node.next_node + +example_list = LinkedList() +example_list.append("first") +example_list.append("second") +example_list.append("fourth") +example_list.insert("third", 2) +example_list.insert("zero", 0) +example_list.insert("last", 5) + +example_list.print_list() +