24. Swap Nodes in Pairs
Problem
https://leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Solution
use two pointers
swap p1.next and p1.next.next, so only let p2 point at one of them then keep replacing the right side of the equal sign.
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
if (!head || !head.next) { return head }
// p1 points at -1
let p1 = { next: head }
head = head.next
while (p1.next && p1.next.next) {
let p2 = p1.next
p1.next = p2.next
p2.next = p1.next.next
p1.next.next = p2
p1 = p2
}
return head
};