面试题目积累2
来源:互联网 发布:windows系统历史 编辑:程序博客网 时间:2024/05/16 13:40
Find Nth last node in a linked list.
Java solution:
Recursive: 递归
public static int kthLastNode (LinkedListNode head, int N){
if (head==null)
return 0;
int i= kthLastNode(head.next, N)+1;
if (i==k)
System.out.println(head.data);
}
设计两个指针,p1先走N步,然后p1,p2同时走,直到p1到尽头,p2的位置就是 Nth to last node。
LinkedListNode NthToLast (LinkedListNode head, int N){
if (N<=0) return null;
LinkedListNode p1=head;
LinkedListNode p2=head;
int i=0;
while (i<N && p1!=null) p1=p1.next; move p1 forward N steps;
if (p1==null) return null;
while (p1!=null){
p1=p1.next;
p2=p2.next;
}
return p2;
}
这样返回的就是倒数第N个元素。
- 面试题目积累2
- 面试题目积累
- 面试题目积累3
- 面试题目积累
- 面试题目积累
- 笔试面试有用题目积累
- JAVA面试积累2
- 面试积累
- 面试积累
- 面试积累
- 面试积累
- 面试积累
- 面试积累
- Java面试题目(2)
- 面试题目2
- 常见面试题目2
- 一道面试题目2
- C#面试题目2
- 面试题目积累
- OSX: 设置Time Server和Time Zone的script
- Fibonacci number
- 如何结合使用 Subversion 和 Eclipse
- 个别控制文件丢失的恢复
- 面试题目积累2
- wayland 编译
- 幾何不變性的簡單討論
- PHP常用正则表达式汇总
- PHP常用特殊运算符号和函数总结
- PHP错误总结
- 部分常用JavaScript代码
- memcache
- Servlet生命周期与工作原理