"""Blind 75, Linked List section (6 problems; Merge K Sorted Lists also counts under Heap)."""
import heapq
from typing import List, Optional

from .structures import ListNode


def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]:
    """LC 206. Walk once, pointing each node back at the previous one."""
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev


def has_cycle(head: Optional[ListNode]) -> bool:
    """LC 141. Floyd: a fast pointer (2 steps) meets the slow one (1 step) only if there is a loop."""
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            return True
    return False


def merge_two_lists(a: Optional[ListNode], b: Optional[ListNode]) -> Optional[ListNode]:
    """LC 21. Dummy head, then always attach the smaller front node."""
    dummy = tail = ListNode()
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next


def merge_k_lists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:
    """LC 23. Min-heap of the current front of each list; the index breaks ties between equal values."""
    heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(heap)
    dummy = tail = ListNode()
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next


def remove_nth_from_end(head: Optional[ListNode], n: int) -> Optional[ListNode]:
    """LC 19. Move a lead pointer n steps ahead, then move both; the trailer stops before the target."""
    dummy = ListNode(0, head)
    lead = trail = dummy
    for _ in range(n):
        lead = lead.next
    while lead.next:
        lead, trail = lead.next, trail.next
    trail.next = trail.next.next
    return dummy.next


def reorder_list(head: Optional[ListNode]) -> None:
    """LC 143. Three known moves: find the middle, reverse the second half, weave the halves together."""
    if not head:
        return
    slow = fast = head
    while fast.next and fast.next.next:
        slow, fast = slow.next, fast.next.next
    second, slow.next = reverse_list(slow.next), None
    first = head
    while second:
        first.next, second.next, first, second = second, first.next, first.next, second.next
