CodeArchon

mediumLinked ListAmazonMeta

Fold Chain

A theatre seating list in a strip must be folded so attendees sit alternately from the front and the back.

Given a linked list `L0 → L1 → … → Ln`, reorder it in place to `L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …`.

Choose approach

1
2
3
mid
4
5
nil
1/5
Narrationstep 1 of 5

Find middle via slow/fast. Middle index = 2 (value 3).

1def fold_chain(head) -> None:
2 if not head or not head.next:
3 return
4 slow = fast = head
5 while fast.next and fast.next.next:
6 slow, fast = slow.next, fast.next.next
7 prev, curr = None, slow.next
8 slow.next = None
9 while curr:
10 curr.next, prev, curr = prev, curr, curr.next
11 a, b = head, prev
12 while b:
13 an, bn = a.next, b.next
14 a.next, b.next = b, an
15 a, b = an, bn
Variables
middle=3

How to think about it

  1. Three classic linked-list sub-tasks composed in order.
  2. Finding the middle sets up the split without computing the length.
  3. Reversing the second half gives us a tail-to-head cursor.
  4. Weaving zips the two halves in place with four rewrites per step.

Edge cases to catch in interview

  • Fewer than 3 nodes — nothing to do.
  • Even length — first half gets the extra node.
  • Clip the first half's tail to null to avoid cycles.

Examples

Example 1[1,5,2,4,3]
{"values":[1,2,3,4,5]}
Example 2[1,4,2,3]
{"values":[1,2,3,4]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed