Gamified challenge · Linked lists
A train is a singly linked list of wagons (ListNodes with a number val and a link next). You get the head wagon train, or null for an empty platform.
Write swapPairs(train) (Python: swap_pairs(train)) that swaps wagons 1 and 2, 3 and 4, and so on, and returns the new head. If the train has an odd number of wagons, the last one stays where it is. Move the wagons by relinking next; don't just swap the numbers.
For 1 → 2 → 3 → 4 return 2 → 1 → 4 → 3; for 1 → 2 → 3 return 2 → 1 → 3.
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google