查看: 90|回覆: 0

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

[複製鏈接]

2

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2009-8-11
發表於 2026-4-27 17:56:00 | 顯示全部樓層 |閲讀模式

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

0:58:19

 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&&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));


来源:https://www.cnblogs.com/KooTeam/p/19939353
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部