Swap Nodes in Pairs
Swap every two neighboring nodes: the 1st with the 2nd, the 3rd with the 4th, and so on. If the length is odd, the last node stays where it is. Return the new head. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
head [1,2,3,4]
returns [2,1,4,3]
2, 1, 4, 3.
Example 2
head [1,2,3]
returns [2,1,3]
The 3 has no partner.
Constraints
0 <= number of nodes <= 100-100 <= Node.val <= 100- Move the nodes themselves or just their values, either is fine
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Values That Appear OnceEasy
- Add Two NumbersMedium
- Add Two Numbers IIMedium
- Cancel Opposite NeighborsMedium
- Delete the Middle NodeMedium
- Evens Before OddsMedium
- Last One StandingMedium
- Length of the CycleMedium