Swap every two adjacent nodes in a singly linked list without changing node values.
Problem
Given the head of a singly linked list, swap every two adjacent nodes and return the new head of the list.
You must swap the nodes themselves, not just their values.
If the list contains an odd number of nodes, the final node should remain in place.
Goal
Rearrange the links so that each pair of neighboring nodes is exchanged in order.
Input Format
- The input is the head of a singly linked list.
- Each node contains an integer value.
- The list is singly linked and may have odd or even length.
Output Format
- Return the head of the linked list after swapping every adjacent pair of nodes.
Constraints
- The list length is at least 0.
- The relative order of nodes inside each swapped pair changes, but no node values should be modified.
- Use extra space for the iterative solution when possible.
Example 1
Input
head = [1,2,3,4]
Output
[2,1,4,3]
Explanation
The first pair (1,2) becomes (2,1) and the second pair (3,4) becomes (4,3).
Example 2
Input
head = [1,2,3]
Output
[2,1,3]
Explanation
The last node has no partner, so it stays in place.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.