タイトル説明
https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
解決
1.再帰を使用します。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
int count = 0;
public ListNode getKthFromEnd(ListNode head, int k) {
return reverse(head,k);
}
public ListNode reverse(ListNode head,int k){
if(head==null) return head;
ListNode last = reverse(head.next,k);//利用栈的回退
count++;//完成一个返回则++,
if(count==k){
return head;
}
return last;
}
}
2.高速ポインタと低速ポインタの特性を利用したダブルポインタ高速ポインタを
最初にkステップ進み、次に2つのポインタが同期して移動します。高速ポインタが最後に到達すると、低速ポインタは下からk番目のノードになります。リンクリストの。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
int count = 0;
public ListNode getKthFromEnd(ListNode head, int k) {
if(head==null)
return null;
ListNode slow = head,fast = head;
while(k>0 && fast!=null){
fast = fast.next;
k--;
}
while(fast!=null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}