Skip to content
BytePatterns

Weave List Halves

MediumLinked Lists#fast-slow-pointers#list-reversal~35m

Problem

Given the head of a singly linked list holding at least one node, rearrange it so the nodes alternate between the front and the back: first node, last node, second node, second-to-last node, and so on. The nodes themselves must be relinked, not copied into a new list. Return the head of the rearranged list.

Examples

Input:  head = 1 -> 2 -> 3 -> 4
Output: 1 -> 4 -> 2 -> 3
Input:  head = 1 -> 2 -> 3
Output: 1 -> 3 -> 2
Why:    an odd length leaves the middle node at the end
Input:  head = 7
Output: 7
Why:    edge case, a single node is already in the required order

Hints

0 / 3

Stuck on the idea rather than the code? Reverse a Linked List covers it.