16. [Linked List]: swap nodes in pairs
Last updated
Last updated
Input: head = [1,2,3,4]
Output: [2,1,4,3]Input: head = []
Output: []Input: head = [1]
Output: [1]/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
const dummy = new ListNode(-1, null);
dummy.next = head;
let prev = dummy;
let curr = head;
while (curr !== null && curr.next !== null) {
const next = curr.next;
const nextnext = curr.next.next;
prev.next = next;
next.next = curr;
curr.next = nextnext;
prev = curr;
curr = nextnext;
}
return dummy.next;
};