博客
关于我
剑指offer删除链表中重复的节点
阅读量:634 次
发布时间:2019-03-14

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

链表是排好序的,且需要删除重复的节点。重复节点指的是连续出现的相同值的节点,例如1,1,2,2,3中的第二个1、第二个2需要被删除。我们需要创建一个新的链表来存储结果,以避免在原链表上进行操作可能带来的复杂性。

步骤如下:

  • 初始化新链表:创建一个新的头节点newHead,并用一个指针tmp来跟踪当前位置。
  • 遍历原链表:从原链表的头节点开始,逐个遍历每个节点。
  • 处理重复节点
    • 如果当前节点的值与下一个节点的值相等,继续遍历,直到找到不相同的节点。
    • 一旦找到不同值的节点,将当前节点连接到tmp后面,并移动指针到下一个节点。
  • 处理非重复节点:如果当前节点的值与下一个节点的值不相等,将当前节点连接到tmp后面,并移动指针到下一个节点。
  • 清除尾部节点:如果最后一个节点是重复节点,设置tmp的下一个节点为null。
  • 代码实现如下:

    public class Solution {    public ListNode deleteDuplication(ListNode pHead) {        if (pHead == null) {            return null;        }        ListNode newHead = new ListNode(-1);        ListNode tmp = newHead;        ListNode cur = pHead;        while (cur != null) {            if (cur.next != null && cur.val == cur.next.val) {                while (cur.next != null && cur.val == cur.next.val) {                    cur = cur.next;                }                cur = cur.next;            } else {                tmp.next = cur;                tmp = tmp.next;                cur = cur.next;            }            tmp.next = null;        }        return newHead.next;    }}

    代码解释

    • 初始化:创建了一个新的链表头newHead,并初始化了tmp指针。
    • 遍历链表:从pHead开始,逐个访问每个节点。
    • 处理重复节点:当发现当前节点的值与下一个节点的值相等时,继续移动cur指针,直到找到不相同的节点。
    • 连接节点:当处理完重复节点后,连接当前节点到tmp后面,并移动指针。
    • 清除尾部节点:最后设置tmp的下一个节点为null,确保尾部节点被删除。

    该方法能够正确处理所有情况,包括链表为空、单个节点以及最后一个节点是重复节点的情况。

    转载地址:http://krhoz.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
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    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解决方法
    查看>>