思路:用两个指针,先让快指针走K-1步,下来快指针和慢指针一起走,直到快指针结束,慢指针所在节点就是单链表倒数第k个节点
public ListNode
findKthToTail(int k
){
if(k
<=0||head
==null
){
return null
;
}
ListNode fast
=this.head
;
ListNode slow
=this.head
;
while(k
-1>0){
if(fast
.next
!=null
){
fast
=fast
.next
;
k
--;
}else{
System
.out
.println("没有这个节点");
return null
;
}
}
while(fast
.next
!=null
){
fast
=fast
.next
;
slow
=slow
.next
;
}
return slow
;
}
转载请注明原文地址: https://mac.8miu.com/read-509808.html