# 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()

