1、题目:24. 两两交换链表中的节点 - 力扣(LeetCode) (leetcode-cn.com)
2、实现:
(1)思路:
(2)代码:
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
let dummy = new ListNode();
dummy.next = head;
let curr = dummy;
while(curr.next !== null && curr.next.next !== null) {
let n1 = curr.next;
let n2 = curr.next.next;
curr.next = n1.next;
n1.next = n2.next;
n2.next = n1;
curr = n1;
}
return dummy.next;
};
3、参考:Leetcode刷题 24 两两交换链表中的节点 Swap Nodes in Pairs_哔哩哔哩_bilibili