https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
解法一: 顺序遍历
先统计出链表有多少个节点n,然后倒数第k个节点就是顺数第n-k+1个节点
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
int n=0;
ListNode cur=head;
while(cur!=null){
n++;
cur=cur.next;
}
cur=head;
int i=0;
while(i<n-k){
cur=cur.next;
i++;
}
return cur;
}
}
//O(n)
//O(1)
解法二:快慢指针
先让快指针先走k步,然后快慢指针一起走,当快指针走完时,慢指针恰好到到达倒数第k个节点
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode slow=head,fast=head;
int i=0;
while(i<k){
fast=fast.next;
i++;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}