Swap nodes in pairs
Mediumlinked listrecursion
Swap every two adjacent nodes: the 1st with the 2nd, the 3rd with the 4th, and so on. Swap the nodes themselves, not their values. With an odd count the last node stays put.
Example 1
Input: head = [1,2,3,4] Output: [2,1,4,3]
Example 2
Input: head = [1,2,3] Output: [2,1,3]
Constraints
- 0 ≤ number of nodes ≤ 100
- 0 ≤ Node.val ≤ 100
Submit checks your solution against 8 tests, including hidden ones.
// Provided by the judge: keep these definitions
class ListNode {
constructor(val = 0, next = null) {
this.val = val
this.next = next
}
}
/**
* @param {ListNode|null} head
* @return {ListNode|null}
*/
function swapPairs(head) {
}