Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
class ListNode {
constructor(val, next=null) {
this.val = val;
this.next = next;
}
}
var swapPairs = function(head) {
const prehead = new ListNode(null, head);
for (let p = prehead; p.next !== null && p.next.next !== null;) {
const p1 = p.next;
const p2 = p1.next; // 0 1 2 3 4
p1.next = p2.next; // 0 1 3 4
p2.next = p1; // 2 1 3 4
p.next = p2; // 0 2 1 3 4
p = p1;
}
return prehead.next
};
console.log(swapPairs(new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))))));
Comments
Post a Comment