建立两个指针,一快一慢,fast,slow
public ListNode
FindKthToTail(ListNode head
,int k
) {
if (head
== null
) {
return null
;
}
int size
= size(head
);
if (k
<= 0 || k
> size
) {
return null
;
}
ListNode fast
= head
;
ListNode slow
= head
;
for (int i
= 0; i
< k
; i
++) {
fast
= fast
.next
;
}
while (fast
!= null
) {
fast
= fast
.next
;
slow
= slow
.next
;
}
return slow
;
}
public int size(ListNode head
) {
int size
= 0;
for (ListNode node
= head
; node
!= null
; node
= node
.next
) {
size
++;
}
return size
;
}
转载请注明原文地址: https://mac.8miu.com/read-510740.html