320. Swap Nodes in Pairs

EasyLinked ListLinked ListPointer Manipulation

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

You must swap the nodes themselves (pointers), not just the values.

If the list has an odd number of nodes, the last node is left in place.

Input: Head of a singly linked list.

Output: Head of the list after pairwise swapping.

Examples

Example 1
Input: [1,2,3,4]
Output: [2,1,4,3]
Explanation: Pair (1,2)→(2,1), pair (3,4)→(4,3). Result: 2→1→4→3.
Example 2
Input: [1,2,3,4,5]
Output: [2,1,4,3,5]
Explanation: Pairs swapped: (1,2)→(2,1), (3,4)→(4,3). Node 5 unchanged.
Example 3
Input: [1]
Output: [1]
Explanation: Single node. No pair to swap. Return as is.

Constraints

Asked by

BloombergMicrosoftAmazonGoogleMeta
Solve this problem in the editor →