《王道数据结构》给出的快慢指针,真是一个不错的好方法啊!
static public ListNode nthToLast(ListNode head, int n) {
// write your code here
ListNode p=head;
while(p!=null&&n!=0){
p=p.next;
n--;
}
if(n!=0)
return null;
ListNode pre=head;
while(p!=null)
{
pre=pre.next;
p=p.next;
}
return pre;
}