博客
关于我
在单链表和双链表中删除倒数第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/

你可能感兴趣的文章
MYSQL语句。
查看>>
MySQL调优是程序员拿高薪的必备技能?
查看>>
MySQL调大sort_buffer_size,并发量一大,查询排序为啥又会变慢
查看>>
Mysql账号权限查询(grants)
查看>>
mysql转达梦7_达梦7的子查询分解示例说明
查看>>
MYSQL输入密码后闪退的解决方法
查看>>
MySQL迁移到达梦:如何轻松、高质量完成迁移任务
查看>>
mysql返回的时间和实际数据存储的时间有误差(java+mysql)
查看>>
mysql还有哪些自带的函数呢?别到处找了,看这个就够了。
查看>>
Mysql进入数据库
查看>>
mysql进阶 with-as 性能调优
查看>>
mysql进阶-查询优化-慢查询日志
查看>>
wargame narnia writeup
查看>>
MySQL进阶篇SQL优化(InnoDB锁问题排查与解决)
查看>>
Mysql进阶索引篇03——2个新特性,11+7条设计原则教你创建索引
查看>>
mysql远程连接设置
查看>>
MySql连接出现1251Client does not support authentication protocol requested by server解决方法
查看>>
Mysql连接时报时区错误
查看>>
MySql连接时提示:unknown Mysql server host
查看>>
MySQL连环炮,你扛得住嘛?
查看>>