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

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

分别实现两个函数,一个可以删除单链表中倒数第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;        }        // K大于链表的长度,直接返回        if (lastKth > 0){            return head;        }        // 删除的是头结点--倒数最后一个-第一个        if (lastKth == 0){            return head.next;        }        // 一般情况        if (lastKth < 0){            cur = head; // 重置当前链表            while(++lastKth != 0){ // 找到的是前一个节点 ++lastKth:这个操作很秀                cur = cur.next; // 向下移动            }            cur.next = cur.next.next; // 找到要删除的节点        }        return head;    }
// 与单链表不同的是需要对last指针进行重置public DoubleNode removeLastKthNode(DoubleNode head, int lastKth){        if (head == null || lastKth < 1){            return head;        }        DoubleNode cur = head;        while(cur != null){            lastKth --;            cur = cur.next;        }        if (lastKth == 0){            head = head.next;            head.last = null; // 区别1            return head;        }        if (lastKth > 0){            return head;        }        if (lastKth < 0){            cur = head;            while(++ lastKth != 0){                cur = cur.next;            }            cur.next = cur.next.next;            if (cur.next.next != null)                cur.next.next.last = cur;        }        return head;    }

参考书目:

《程序员代码面试指南 IT名企算法与数据结构题目最优解》

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

你可能感兴趣的文章
Manjaro 24.1 “Xahea” 发布!具有 KDE Plasma 6.1.5、GNOME 46 和最新的内核增强功能
查看>>
mapping文件目录生成修改
查看>>
MapReduce程序依赖的jar包
查看>>
mariadb multi-source replication(mariadb多主复制)
查看>>
MaterialForm对tab页进行隐藏
查看>>
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
MQTT工作笔记0009---订阅主题和订阅确认
查看>>
ms sql server 2008 sp2更新异常
查看>>
MS UC 2013-0-Prepare Tool
查看>>