"""Singly linked list with in-place reversal.

Idea
----
Each node stores a value and a pointer to the next node. Inserting at the
head is O(1) and needs no shifting, but finding the i-th element means
walking i links. Reversal is the canonical pointer exercise: walk the list
once, turning each ``next`` pointer around with three variables
(``prev``, ``current``, ``next``).

Complexity
----------
push_front: O(1); append: O(1) (we keep a tail pointer)
find / remove: O(n); reverse: O(n) time, O(1) space
"""

from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from typing import Any


@dataclass
class Node:
    value: Any
    next: "Node | None" = None


class LinkedList:
    def __init__(self, values: Iterable[Any] = ()) -> None:
        self.head: Node | None = None
        self.tail: Node | None = None
        self._size = 0
        for v in values:
            self.append(v)

    def push_front(self, value: Any) -> None:
        self.head = Node(value, self.head)
        if self.tail is None:
            self.tail = self.head
        self._size += 1

    def append(self, value: Any) -> None:
        node = Node(value)
        if self.tail is None:
            self.head = self.tail = node
        else:
            self.tail.next = node
            self.tail = node
        self._size += 1

    def remove(self, value: Any) -> bool:
        """Remove the first node holding ``value``; return True if found."""
        prev: Node | None = None
        cur = self.head
        while cur is not None:
            if cur.value == value:
                if prev is None:
                    self.head = cur.next
                else:
                    prev.next = cur.next
                if cur is self.tail:
                    self.tail = prev
                self._size -= 1
                return True
            prev, cur = cur, cur.next
        return False

    def reverse(self) -> None:
        prev: Node | None = None
        cur = self.head
        self.tail = cur
        while cur is not None:
            nxt = cur.next
            cur.next = prev
            prev, cur = cur, nxt
        self.head = prev

    def __iter__(self) -> Iterator[Any]:
        cur = self.head
        while cur is not None:
            yield cur.value
            cur = cur.next

    def __len__(self) -> int:
        return self._size
