题解 | 链表中倒数最后k个结点
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
import java.util.*;
public class Solution {
public ListNode FindKthToTail (ListNode pHead, int k) {
//测试2{如果k为0}
if(k == 0) return null;
ListNode tmp = reverse(pHead);
ListNode last = tmp;
for(int i =1 ;i <k;i++){
//测试1{如果k比链表还长}
if(tmp == null) return null;
tmp = tmp.next;
}
reverse(last);
return tmp;
}
public ListNode reverse(ListNode root){
ListNode pre = null;
ListNode next = null;
while(root != null){
next = root.next;
root.next = pre;
pre = root;
root = next;
}
return pre;
}
}
查看15道真题和解析
