Deal From Both Ends
Medium · Linked Lists · about 30 min
A card dealer holds a deck as a linked list, top to bottom. She deals from both ends in turn: the first card, then the last card, then the second card, then the second-to-last card, and so on until every card is dealt once.
Build the chain from values, rearrange the nodes into that dealing order (relink them, don't create new ones), and return the new order as a list.
- If the deck has an odd number of cards, the middle card is dealt last.
- An empty deck gives
[].
Example: deal_both_ends([1, 2, 3, 4, 5]) → [1, 5, 2, 4, 3]
Hints
- Use a slow pointer that moves one step and a fast one that moves two to find the middle node.
- Cut the chain after the middle and reverse the second half, so its first node is the last card.
- Now weave: take one node from the first half, then one from the reversed half, until the reversed half runs out.
Learn the pattern first: the Linked Lists lesson.
More Linked Lists problems
- Merge Two Delivery Routes (Easy)
- Cancel the K-th Last Booking (Easy)
- Flip a Section of the Parade (Medium)
- Does the Treasure Hunt Loop? (Medium)
- Add Two Digit Chains (Medium)