Python coding

Node at the halfway point

Write middle_node(head): given the first node of a singly linked list, return its middle node (not its value). With an even number of nodes there are two middle nodes: return the second one. For an empty list return None. Each ListNode has val and next.

Aim for a single pass, without counting the nodes first.

The tests call the provided run_middle_node(values), which builds the list from values and returns the values from your node to the end of the list.

  • run_middle_node([1,2,3,4,5]) → [3,4,5]
  • run_middle_node([1,2,3,4,5,6]) → [4,5,6]
  • run_middle_node([7]) → [7]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Use two pointers that start at the head and move at different speeds.

Hint 2

slow moves one node while fast moves two. When fast runs off the end, slow has covered half the distance.

Hint 3

The loop condition picks the middle: while fast and fast.next lands on the second middle of an even list and also survives an empty list.

Solution and why it works
pythonO(n) · O(1)
# --- your code ---
def middle_node(head: "ListNode | None") -> "ListNode | None":
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
    return slow                  # fast ran off the end: slow is halfway


# --- provided: do not edit ---
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def build_list(values: list[int]) -> ListNode | None:
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_values(head: ListNode | None, limit: int) -> list[int]:
    out = []
    while head is not None:
        if len(out) == limit:
            raise ValueError("the result has more nodes than the input: is there a cycle?")
        out.append(head.val)
        head = head.next
    return out


def run_middle_node(values: list[int]) -> list[int]:
    return to_values(middle_node(build_list(values)), len(values))

fast covers two nodes for every one that slow covers, so when fast runs off the end slow is halfway: one pass, no length needed. The loop condition decides which middle you get. while fast and fast.next stops on the second middle of an even list and is safe on an empty one; while fast.next and fast.next.next stops on the first middle and crashes when head is None.