Swap Nodes in Pairs

Given the head of a linked list, swap every two adjacent nodes and return the head of the modified list.

You must swap the nodes themselves, not just their values. In other words, you may not modify the values stored in the list's nodes.

Example 1
[1] -> [2] -> [3] -> [4] -> null
---
[2] -> [1] -> [4] -> [3] -> null
Inputhead = [1,2,3,4]
Output[2,1,4,3]
The first pair 1 and 2 is swapped, and the second pair 3 and 4 is swapped.
Example 2
null
---
null
Inputhead = []
Output[]
An empty list has no adjacent nodes to swap, so it remains empty.

Constraints

  • The number of nodes in the list is in the range [0, 100]
  • 0 <= Node.val <= 100

Asked at 16 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate