swap-nodes.js (851B)
1 //Swap nodes that are next to each other. Ex. 2 //[x1 , y1 , x2 , y3] -> [y1 , x1 , y2, x2] 3 //This solution has a time compexity of O(n) where n 4 //is the length of the linked list. 5 //Time: 54ms Beats: 82.81% 6 //Memory: 42.2MB Beats: 40.88% 7 8 /** 9 * Definition for singly-linked list. 10 * function ListNode(val, next) { 11 * this.val = (val===undefined ? 0 : val) 12 * this.next = (next===undefined ? null : next) 13 * } 14 */ 15 /** 16 * @param {ListNode} head 17 * @return {ListNode} 18 */ 19 var swapPairs = function(head) { 20 if(head == null){ 21 return head; 22 } 23 if(head.next == null){ 24 return head; 25 } 26 let itr1 = head; 27 let itr2 = head?.next; 28 while(itr2 != null){ 29 let temp = itr1.val; 30 itr1.val = itr2.val; 31 itr2.val = temp; 32 itr1 = itr2?.next; 33 itr2 = itr1?.next; 34 } 35 return head; 36 };