博客
关于我
在单链表和双链表中删除倒数第K个节点
阅读量:401 次
发布时间:2019-03-05

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

删除链表中的倒数第K个节点

在编程中,链表的操作是一个非常基础但重要的技能。以下,我们将分别实现两个函数:一个用于删除单链表中倒数第K个节点,另一个用于删除双链表中倒数第K个节点。

单链表删除倒数第K个节点

public static Node removeLastKthNode(Node head, int lastKth) {    if (head == null || lastKth < 1) {        return head;    }    Node cur = head;    // 第一遍遍历,计算总长度    while (cur != null) {        lastKth--;        cur = cur.next;    }    // 如果lastKth大于链表长度,直接返回头节点    if (lastKth > 0) {        return head;    }    // 如果lastKth为0,删除最后一个节点    if (lastKth == 0) {        return head.next;    }    // 一般情况,删除倒数第K个节点    cur = head;    while (++lastKth != 0) {        cur = cur.next;    }    cur.next = cur.next.next;    return head;}

双链表删除倒数第K个节点

public static DoubleNode removeLastKthNode(DoubleNode head, int lastKth) {    if (head == null || lastKth < 1) {        return head;    }    DoubleNode cur = head;    // 第一遍遍历,计算总长度    while (cur != null) {        lastKth--;        cur = cur.next;    }    // 如果lastKth大于链表长度,直接返回头节点    if (lastKth == 0) {        head = head.next;        head.last = null;        return head;    }    // 如果lastKth大于链表长度,直接返回头节点    if (lastKth > 0) {        return head;    }    // 一般情况,删除倒数第K个节点    cur = head;    while (++lastKth != 0) {        cur = cur.next;    }    DoubleNode nextNode = cur.next;    cur.next = nextNode;    if (nextNode != null) {        nextNode.last = cur;    }    return head;}

代码解释

单链表删除函数

  • 初始检查:首先检查链表是否为空或lastKth小于1,如果是,直接返回头节点。
  • 计算链表长度:通过遍历链表,计算链表的总长度,并更新lastKth的值。
  • 处理特殊情况
    • 如果lastKth大于链表长度,直接返回头节点。
    • 如果lastKth等于0,删除最后一个节点。
  • 删除倒数第K个节点:从头节点开始遍历,直到找到需要删除的节点,并调整指针。
  • 双链表删除函数

  • 初始检查:与单链表删除函数类似,首先检查链表是否为空或lastKth小于1。
  • 计算链表长度:同样通过遍历链表,计算链表的总长度。
  • 处理特殊情况
    • 如果lastKth等于0,删除最后一个节点,并重置last指针。
    • 如果lastKth大于链表长度,直接返回头节点。
  • 删除倒数第K个节点:从头节点开始遍历,找到需要删除的节点,并调整前后节点的指针。
  • 总结

    这些函数通过两次遍历链表,分别实现了删除单链表和双链表中倒数第K个节点的功能。需要注意的是,在双链表中,删除节点时需要同时处理前后节点的指针,确保链表的完整性。

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

    你可能感兴趣的文章
    ProjectEuler 2
    查看>>
    projection介绍及EPSG:4326和EPSG:3857的投射转换
    查看>>
    project打开文件时,显示无法识别此文件格式?
    查看>>
    Prometheus + Grafana on Kubernetes部署
    查看>>
    prometheus + grafana进行服务器资源监控
    查看>>
    Prometheus Alertmanager 告警配置详解
    查看>>
    Prometheus Grafana 展示平台
    查看>>
    Prometheus pushgateway使用详解
    查看>>
    Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
    查看>>
    Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
    查看>>
    Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
    查看>>
    Prometheus 云原生 - 监控 Linux、MySQL、Redis、RabbitMQ、Docker、SpringBoot 3.x
    查看>>
    Prometheus 介绍
    查看>>
    Prometheus 安全配置详解
    查看>>
    prometheus 安装node_exporter, node_exporter 安装最新版 普罗米修思安装监控服务器client
    查看>>
    Prometheus 安装部署实战
    查看>>
    prometheus 持久化存储方案
    查看>>
    Prometheus 监控系统企业级实战
    查看>>
    Prometheus 监控系统简介
    查看>>
    Prometheus 配置详解
    查看>>