Implement an algorithm to find the kth to last element of a singly linked list.

实现一个算法寻找链表中倒数第K个数..

解答:

关于链表的问题,书中也提到了关键的两个技巧,一个是递归;另一个是 The"Runner"Technique,也就是使用两个指针同时遍历链表的方式。这道题可以分别用这两种方法来解决。

import java.util.HashMap;

public class List {
int data;
List next; public List(int d) {
this.data = d;
this.next = null;
} public void appendToTail(int d) {
List end = new List(d);
List n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
} public void print() {
List n = this;
System.out.print("{");
while (n != null) {
if (n.next != null)
System.out.print(n.data + ", ");
else
System.out.println(n.data + "}");
n = n.next;
}
} public int nthToLast(int n) {
if (this.next == null) {
if (n == 0)
System.out.println(this.data);
return 0;
}
int i = this.next.nthToLast(n) + 1;
if (i == n)
System.out.println(this.data);
return i;
} public void nthToLast1(int n) {
List m = this;
List pt = this;
for (int i = 0; i < n; i++){
if(pt.next == null)
return ;
pt = pt.next;
}
while(pt.next != null)
{
m = m.next;
pt = pt.next;
}
System.out.println(m.data);
} public static void main(String args[]) {
List list = new List(0);
list.appendToTail(1);
list.appendToTail(2);
list.appendToTail(3);
list.appendToTail(4);
list.appendToTail(5);
list.appendToTail(6);
list.appendToTail(7);
list.appendToTail(8);
list.appendToTail(9);
list.print();
list.nthToLast(10);
list.nthToLast1(10);
}
}

最新文章

  1. 《月之猎人 (Moon Hunters)》主角设计
  2. IIS与Apache共用80端口方法
  3. 字节流与字符流(FileInputStream类和FileOutputStream类)
  4. &lt;读书笔记&gt;软件调试之道 :实证方法
  5. asp.net 去掉重复的querystring
  6. sqlserver中几种典型的等待
  7. hdu 1078 FatMouse and Cheese 记忆化dp
  8. [Linux] PHP程序员玩转Linux系列-telnet轻松使用邮箱
  9. centos下 apache+mysql+php的安装
  10. Android 导入v7包常见错误,以及项目引用v7包错误解决
  11. 被final关键字坑了
  12. springboot v2.0.3版本多数据源配置
  13. 简单的ld链接脚本学习
  14. 关闭pycharm自动更新
  15. js-运动函数包
  16. java运行报错:nested exception is java.lang.NoSuchFieldError: INSTANCE,但使用@Test测试是好的
  17. Javascript 对象继承 原型链继承 对象冒充 call 混合方式
  18. map练习
  19. Java基础教程(15)--枚举类型
  20. Android TextView文字透明度和背景透明度设置

热门文章

  1. 移动端转PC --&gt; PC跳转移动端
  2. 从Delphi 7升级到Delphi XE
  3. 怎样使用 iOS 7 的 AVSpeechSynthesizer 制作有声书(2)
  4. Java面试求职之==与equals()差别
  5. [转] C++指针加整数、两个指针相减的问题
  6. Android(java)学习笔记219:开发一个多界面的应用程序之两种意图
  7. (转)ECSHOP给分类添加代表图
  8. MemCachedClient数据写入的三个方法
  9. cxf WebService整理 (基于注解)
  10. Ubuntu12.4 64位 安装 arm linux gcc 4.3.2