Swap Nodes in Pairs

Medium Linked List AI round

head is the head of a singly linked list, which may be empty.

Swap the nodes two by two: the first with the second, the third with the fourth, and so on. When the list has an odd number of nodes, the last one stays where it is. Swap the nodes themselves by changing their links: each node keeps its value.

Return the head of the list after the swaps, or null if it is empty.

Example 1

Input: head = [6,1,8,3,9]
Output: [1,6,3,8,9]

6 and 1 swap places, then 8 and 3. 9 has no node after it to pair with, so it stays last.

Example 2

Input: head = [-4,5,-4,5]
Output: [5,-4,5,-4]

Example 3

Input: head = [42]
Output: [42]

One node has nothing to swap with.

Constraints

  • 0 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ node.val ≤ 10⁹

Watch the explanation

More Linked List

All Linked List problems