查看: 73|回复: 0

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

[复制链接]

0

主题

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.

在本版发帖返回顶部