剑指-22
https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
- 使用最简单的思路,遍历整个链表
- 使用双指针,可以不用遍历整个链表
1.先将两个指针指向头结点
2.fast 向前移动k步,然后fast与slow就相差k步
3.return slow
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *fast = head;
ListNode *slow = head;
while(fast && k>0){
fast = fast->next;
k--;
}
while(fast){
fast = fast->next;
slow = slow->next;
}
return slow;
}
};