Python coding

Interleave the two ends of a list

Write fold_list(head): reorder a singly linked list in place so it alternates between its front and its back: first node, last node, second node, second-to-last node, and so on. 1 → 2 → 3 → 4 → 5 becomes 1 → 5 → 2 → 4 → 3. The first node stays first, so return nothing. The list may be empty (head is None). Each ListNode has val and next.

Move the nodes instead of rewriting their values, in O(n) time and O(1) extra memory (no list of nodes).

The tests call the provided run_fold_list(values), which builds the list from values, calls your function and returns the values from the original first node onwards.

Besides the tests, one large input (a 10,000-node list) with a ~180 ms limit (scaled to your device's speed): brute force won't pass.

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

It is three small problems in a row: find the middle, reverse the second half, then weave the two halves together.

Hint 2

Stop slow on the last node of the first half and cut there (slow.next = None); otherwise the halves stay joined and the weave ends in a cycle.

Hint 3

Weave by taking one node from each half in turn, saving both next pointers before re-linking. The reversed half is never longer, so loop while it has nodes.

Solution and why it works
pythonO(n) · O(1)
# --- your code ---
def fold_list(head: "ListNode | None") -> None:
    if head is None:
        return
    slow = fast = head
    while fast.next is not None and fast.next.next is not None:
        slow = slow.next                 # ends on the last node of the first half
        fast = fast.next.next
    back, slow.next = slow.next, None    # cut the list in two
    prev = None
    while back is not None:              # reverse the second half
        nxt = back.next
        back.next = prev
        prev, back = back, nxt
    front, back = head, prev
    while back is not None:              # weave: one node from the front, one from the back
        front_next, back_next = front.next, back.next
        front.next = back
        back.next = front_next
        front, back = front_next, back_next


# --- 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_nodes(head: ListNode | None, limit: int) -> list[ListNode]:
    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)
        head = head.next
    return out


def run_fold_list(values: list[int]) -> list[int]:
    head = build_list(values)
    given = to_nodes(head, len(values))
    try:
        fold_list(head)
        if any(n.val != v for n, v in zip(given, values)):
            raise ValueError("move the nodes, not their values: every node must keep its value")
        return [n.val for n in to_nodes(head, len(values))]
    finally:
        for n in given:                  # free node by node: a long chain freed at once overflows Pyodide's stack
            n.next = None

The back half is visited backwards, and a singly linked list only goes forwards, so reverse that half first. Fast/slow pointers find the end of the first half in one pass; cutting there and reversing the rest leaves two forward lists (1 → 2 → 3 and 5 → 4) to weave one node at a time. Each step is O(n) time and O(1) memory. The trap is the brute force: walking to the tail again for every node is O(n²).