博客
关于我
在单链表和双链表中删除倒数第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 client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>