Ctrl K

Trade Places in Twos

Medium
You are given a singly linked list head. Group its nodes into consecutive pairs (first with second, third with fourth, and so on) and swap the two nodes in every pair. If the number of nodes is odd, the last one stays where it is. Return the head of the resulting list. Move the nodes themselves by rewiring the next links; do not just swap the values stored in them.
Example 1
head=list_node([4, 8, 15, 16, 23]) → [8, 4, 16, 15, 23]

The pairs (4, 8) and (15, 16) trade places; 23 has no partner and stays at the end.

Example 2
head=list_node([0, 9]) → [9, 0]

The only pair trades places.

Example 3
head=list_node([]) → None

An empty list stays empty.

Constraints
  • The list has between 0 and 100 nodes
  • 0 ≤ Node.val ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAdding Digit Lists MediumList Folded From Both Ends MediumLeaders of a List MediumZip Two Sorted Chains EasyReversing a List in Blocks Hard
loading Python…
Input
head=list_node([4, 8, 15, 16, 23])
Expected
[8, 4, 16, 15, 23]

Run checks the first 3 tests in your browser. Submit checks all 94 tests on the server, hidden ones included.