Problem 228614 · medium · Level 02 Linear Data Structures

Swap Neighbouring Nodes

linked list · pointer manipulation · dummy node

Given the head of a singly linked list, swap every pair of adjacent nodes and return the head. The first node swaps with the second, the third with the fourth, and so on. A leftover last node stays where it is. Swap the nodes themselves; do not just exchange the values stored in them. One test checks this: original_positions(values) builds a list from values, runs your swap_pairs and returns, for each node of the result, the 0-based position that node had in the original list, so original_positions([6, 8, 1, 4]) must be [1, 0, 3, 2].

Examples

Input:  head = 6 -> 8 -> 1 -> 4
Output: 8 -> 6 -> 4 -> 1

Input:  head = 5 -> 9 -> 2
Output: 9 -> 5 -> 2

Constraints

  • 0 <= number of nodes <= 10**4
  • Target: O(n) time, O(1) extra space

Goals

  • Rewire three pointers to swap two adjacent nodes
  • Advance by two nodes per step and stop cleanly on an odd tail
Starting Python…