查看: 6|回复: 0

LeetCode每日一练【24】

[复制链接]

1

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2009-2-4
发表于 2022-5-5 10:08:00 | 显示全部楼层 |阅读模式

Swap Nodes in Pairs

我的提交

介绍

罗里吧嗦

思路

  1. 循环遍历链表
  2. 交换两个节点
  3. 找到下两个节点,继续进行交换

代码

/*
 * @Author: fox
 * @Date: 2022-05-05 08:01:04
 * @LastEditors: fox
 * @LastEditTime: 2022-05-05 10:04:31
 * @Description: https://leetcode.com/problems/swap-nodes-in-pairs/
 */

/**
 * @description: Runtime: 84.28%  Memory Usage: 50.14%
 * @param {*}
 * @return {*}
 */
class ListNode {
    constructor (val, next) {
        this.val = (val === undefined ? 0 : val);
        this.next = (next === undefined ? null : next);
    }
}

const swapPairs = (head) => {
    if (!head || head.length === 0) return null;
    if (head.length === 1) return head[0];

    const listnode = new ListNode(0, head);
    let pre = listnode;
    let cur = pre.next.next;

    while (pre && cur) {
        // 1. 节点交换
        pre.next.next = cur.next;
        cur.next = pre.next;
        pre.next = cur;

        // 2. 移动节点
        if (!cur.next.next || !cur.next.next.next) break;
        pre = cur.next;
        cur = pre.next.next;
    }
    return listnode.next;
}


来源:https://www.cnblogs.com/mapodoufu/p/16223683.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

在本版发帖返回顶部