博客
关于我
【牛客网-名企高频面试题】NC50 链表中的节点每k个一组翻转
阅读量:361 次
发布时间:2019-03-04

本文共 1314 字,大约阅读时间需要 4 分钟。

解题思路

本题要求将给定一个头节点的链表,其中每k个节点为一个组,逆序交换这些组的顺序。例如,当k=2时,链表1→2→3→4→5→6→7→8→9→10,反转后的链表应为7→8→1→2→9→10→3→4→5→6。

实现思路如下:

  • 首先检查特殊情况:如果链表为空或只有一个节点,直接返回原链表;如果k小于2,同样返回原链表。

  • 创建一个辅助节点dummy,用于简化链表操作,其下一个节点指向原链表的头节点。

  • 计算链表的总长度len

  • 遍历len/k次,每次处理一个k长度的组,将该组的节点逆序插入到结果链表中。

  • 在每次处理k长度的组时,从当前节点开始,提取k个节点,逆序连接到辅助链表的末尾。

  • 更新辅助链表的头节点和当前节点。

  • 最终,返回dummy节点的下一个节点,即为反转后的链表。

    代码实现

    public class Solution {    public static ListNode reverseKGroup(ListNode head, int k) {        if (head == null || head.next == null || k < 2) {            return head;        }        ListNode dummy = new ListNode(0);        dummy.next = head;        ListNode pre = dummy, cur = head, temp;        int len = 0;        // 计算链表长度        while (head != null) {            len++;            head = head.next;        }        // 处理每k个节点的组        for (int i = 0; i < len / k; i++) {            for (int j = 1; j < k; j++) {                temp = cur.next;                cur.next = temp.next;                temp.next = pre.next;                pre.next = temp;            }            pre = cur;            cur = cur.next;        }        return dummy.next;    }}

    代码解释:

  • 首先检查特殊情况,确保在处理前不会出错。

  • 使用dummy节点简化链表操作,避免了多次创建临时节点。

  • 计算链表长度len,用于确定需要处理多少组。

  • 遍历len/k次,每次处理一个k长度的组。

  • 在处理每个k长度的组时,逐个节点逆序连接到结果链表中。

  • 更新辅助节点precur,逐步构建反转后的链表。

  • 这种方法通过逐步处理每k个节点的组,实现了对整体链表的逆序交换,时间复杂度为O(n),空间复杂度为O(1)。

    转载地址:http://gser.baihongyu.com/

    你可能感兴趣的文章
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>