题目描述
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步,然后两个指针同步走,当快指针走到头时,慢指针就是链表倒数第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;
}
}