草船等东风 發表於 2026-4-27 17:56:00

24. 两两交换链表中的节点

<h2 id="24-两两交换链表中的节点">24. 两两交换链表中的节点</h2>
<p>0:58:19</p>
<pre><code class="language-js"> 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) {
    // 判断head是否为空
    if(!head)return null;
    // 将相邻的两个链表进行反转
    let ret = new ListNode(-1,head),temp=ret;
    while(temp.next&amp;&amp;temp.next.next){
      let pre = temp.next,cur = temp.next.next;
      temp.next = cur;
      pre.next = cur.next;
      cur.next = pre;
      temp.next = cur;
      temp = pre;
    }
    // 然后返回链表
    return ret.next;
};

let head = new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4))));
console.log(swapPairs(head));
</code></pre><br><br>
来源:https://www.cnblogs.com/KooTeam/p/19939353
頁: [1]
查看完整版本: 24. 两两交换链表中的节点