2.2---找链表倒数第K个结点
2015-12-17 12:31
267 查看
答案,注意,一种是递归,另一种是迭代,那么巧妙利用双指针:
迭代:
View Code
递归:
迭代:
public static LinkedListNode nthToLast(LinkedListNode head, int n) { LinkedListNode p1 = head; LinkedListNode p2 = head; if (n <= 0) return null; // Move p2 n nodes into the list. Keep n1 in the same position. for (int i = 0; i < n - 1; i++) { if (p2 == null) { return null; // Error: list is too small. } p2 = p2.next; } if (p2 == null) { // Another error check. return null; } // Move them at the same pace. When p2 hits the end, // p1 will be at the right element. while (p2.next != null) { p1 = p1.next; p2 = p2.next; } return p1; }
View Code
递归:
public static int nthToLastR1(LinkedListNode head, int n) { if (n == 0 || head == null) { return 0; } int k = nthToLastR1(head.next, n) + 1; if (k == n) { System.out.println(n + "th to last node is " + head.data); } return k; }
相关文章推荐
- 也谈exe文件关联修复
- android popupwindow的使用以及点击空白处消失 以及Dialog框的使用
- 求两个时间差的天数、小时、分钟、秒
- 托盘图标的制作,点击与触发
- 轻量级JavaEE企业应用实战(六)
- 95,autorelease的注意事项
- No important thing
- iOS工作小常识
- iOS 【UIKit-iOS事件之触摸事件】
- retain、copy、mutableCopy的区别(深拷贝 浅拷贝)
- 如何获取选中的复选框
- Java 斐波那契数列
- 第一次了解GitHub,在Windows下使用GitHub
- 深入理解Java的接口和抽象类(转载---写的非常好~)
- sendmsg() Permission denied
- [网络管理]共享文件之卷影副本的使用
- Spring数据源配置总结
- python科学计算库安装
- python科学计算库安装
- python科学计算库安装