思路:暴力
// @Title: 训练计划 II (训练计划 II)
// @Author: qisiii
// @Date: 2022-02-20 17:58:45
// @Runtime: 0 ms
// @Memory: 39.2 MB
// @comment: 暴力
// @flag: BLUE
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode temp=head;
int count=0;
while(temp!=null){
count++;
temp=temp.next;
}
while(count!=k){
count--;
head=head.next;
}
return head;
}
}
思路:快慢指针
// @Title: 训练计划 II (训练计划 II)
// @Author: qisiii
// @Date: 2022-02-20 18:21:25
// @Runtime: 0 ms
// @Memory: 39.2 MB
// @comment: 快慢指针
// @flag: GREEN
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode slow=head;
while(slow!=null&&k>0){
k--;
slow=slow.next;
}
ListNode fast=slow;
while(fast!=null){
head=head.next;
fast=fast.next;
}
return head;
}
}