面试题目积累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个元素。