You are given the head of a singly linked list. Your task is to reverse every two consecutive nodes in the linked list and return the head of the modified list. If the linked list contains an odd number of nodes, the last node remains unchanged.
Example 1
Input: head = [1,2,3,4,5,6]
Output: [2,1,4,3,6,5]
Explanation: Each pair of adjacent nodes is reversed.
Example 2
Input: head = [1,2,3,4,5]
Output: [2,1,4,3,5]
Explanation: The last node has no pair, so it remains unchanged.
Example 3
Input: head = [10]
Output: [10]
Explanation: A single-node linked list remains unchanged.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 2 3 4
2 1 4 3
1 2 3 4 5
2 1 4 3 5