Skip to content
Decoder

Swap Nodes in Pairs

Medium

Problem

You get the head of a linked list. Swap every two adjacent nodes: the 1st with the 2nd, the 3rd with the 4th, and so on, and return the new head. A last node without a partner stays where it is. Change the links, not the values stored in the nodes.

Example 1

Input
1
Output
2 -> 3 -> 4 → 2 -> 1 -> 4 -> 3

Example 2

Input
1
Output
2 -> 3 → 2 -> 1 -> 3

Example 3

Input
(empty)
Output
(empty)

Constraints

  • 0 <= number of nodes <= 100
  • 0 <= Node.val <= 100

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.