Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Pointing to every active node is an easy way to keep on track.
/**
this.val = val;
this.next = null;
@return {ListNode} */ let swapPairs = function(head) { const prehead = { next: head }
for (let p = prehead; p.next !== null && p.next.next !== null;) { const p1 = p.next const p2 = p1.next p1.next = p2.next p2.next = p1 p.next = p2 p = p1 }
return prehead.next };
Template generated via Leetmark.