You get the head of a singly linked list. Walk it from the front in pairs: the 1st and 2nd nodes form a pair, then the 3rd and 4th, and so on. Swap the two nodes of every pair and return the head of the new list. If the list has an odd length, the last node has no partner and stays where it is.
Move the nodes themselves rather than swapping the values stored in them.
The list splits into three pairs, and the two nodes in each pair trade places.
4 and 6 swap. 1 is left without a partner, so it stays last.
An empty list has no pairs to swap.
Constraints
0 and 1000 nodes.0 <= Node.val <= 1000Put a dummy node in front of the head. Then every pair, the first one included, has a node before it whose next must change.
Swapping two values would be one line. The statement rules that out: the nodes themselves have to move. In a singly linked list, "moving" a node means changing the arrows that lead into and out of it.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium