Swap Nodes in Pairs
Swap every two adjacent nodes in a singly-linked list and return the new head.
Given the head of a singly-linked list, swap every two adjacent nodes and return the head of the resulting list.
You must actually rearrange the nodes themselves (not just swap the values stored inside them). If the list has an odd number of nodes, the final node is left in place, unswapped.
Example 1
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2
Input: head = [1,2,3]
Output: [2,1,3]
Explanation: The trailing node with no partner is left unswapped.
Example 3
Input: head = []
Output: []
Explanation: An empty list has nothing to swap.
Constraints
- The number of nodes in the list is in the range [0, 100].
- 0 <= Node.val <= 100
Follow-up
Can you solve it without modifying the values stored in the nodes, only rearranging the nodes themselves?
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
No test cases yet.