算法思想: 定义快慢指针,先让快的走k-1步,然后快慢一起走,等快的走完,慢的就走到了倒数第k个节点。
java代码
public ListNode
findKthToTail(int k
){
if(k
<0){
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("没有这个节点");
}
}
while(fast
.next
!=null
) {
fast
= fast
.next
;
slow
= slow
.next
;
}
return slow
;
}
转载请注明原文地址: https://mac.8miu.com/read-516712.html