一个指针先走到k位置,然后两个指针同时走,当快的指针走到了最后时,慢的指针也就到了倒数第k个元素位置。
public Node findLastIndexNode(int index) {
Node temp = head.next;
Node temp2 = head.next;
if(index<=0) {
System.out.println("输入错误");//只能是倒数第一第二这样
return null;
}
int i=1;
for(;i<index;i++) {//快指针先走到k位置
if(temp.next==null) {
break;
}
temp = temp.next;
}
if(i<index) {//检查快指针是否走到了k位置,如果没有就说明链表的长度不够。
System.out.println("输入的数值过大");
return null;
}
while(temp.next!=null) {
temp = temp.next;
temp2 = temp2.next;
}
return temp2;
}