64 lines
1.5 KiB
Python
64 lines
1.5 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from typing import Generic, Optional, TypeVar
|
|
|
|
T = TypeVar("T")
|
|
|
|
|
|
# A single node containing data and a reference to the next node
|
|
@dataclass
|
|
class Node(Generic[T]):
|
|
data: T
|
|
next: Optional["Node[T]"]
|
|
|
|
|
|
# The main wrapper for the linked list tracking the head node
|
|
class LinkedList(Generic[T]):
|
|
def __init__(self) -> None:
|
|
self._head: Optional[Node[T]] = None
|
|
|
|
# Add a new element to the front of the list
|
|
def push_front(self, data: T) -> None:
|
|
self._head = Node(data, self._head)
|
|
|
|
# Remove and return the front element of the list
|
|
def pop_front(self) -> Optional[T]:
|
|
if self._head is None:
|
|
return None
|
|
data = self._head.data
|
|
self._head = self._head.next
|
|
return data
|
|
|
|
# Read the front element without removing it
|
|
def peek_front(self) -> Optional[T]:
|
|
return self._head.data if self._head else None
|
|
|
|
|
|
def main() -> None:
|
|
lst: LinkedList[int] = LinkedList()
|
|
count = 0
|
|
message1 = "hello world"
|
|
|
|
# Demonstrate pushing items
|
|
lst.push_front(10)
|
|
count += 1
|
|
lst.push_front(20)
|
|
count += 1
|
|
lst.push_front(30)
|
|
count += 1
|
|
|
|
# Demonstrate peeking at the top item
|
|
top = lst.peek_front()
|
|
if top is not None:
|
|
print(f"Top element: {top}\ncount: {count}") # Output: 30
|
|
print(message1)
|
|
|
|
# Demonstrate popping items
|
|
while (value := lst.pop_front()) is not None:
|
|
print(f"Popped: {value}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|