给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
var swapPairs = function (head) {
if (head === null || head.next === null) {
return head;
}
const dummy = new ListNode();
let pre = dummy;
let cur = head;
while (cur && cur.next) {
pre.next = cur.next;
cur.next = pre.next.next;
pre.next.next = cur;
pre = cur;
cur = cur.next;
}
return dummy.next;
};