All problems

Swap Nodes in Pairs

Medium · linked list

You are given the head of a singly linked list. Walk along it in pairs: the 1st and 2nd nodes trade places, then the 3rd and 4th, then the 5th and 6th, and so on.

If the list has an odd number of nodes, the last node has no partner and stays where it is. Return the head of the rearranged list. An empty list stays empty.

The nodes you receive are ListNode objects with a val and a next.

Examples

Example 1

Input: head = [1, 2, 3, 4]

Output: [2, 1, 4, 3]

Nodes 1 and 2 swap, then nodes 3 and 4 swap.

Example 2

Input: head = [5, 6, 7]

Output: [6, 5, 7]

The last node 7 has no partner, so it stays at the end.

Example 3

Input: head = []

Output: []

Constraints