题目:

/**
 * 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* fhead=new ListNode(NULL);
        fhead->next=head;
        ListNode* slow=fhead;
        ListNode* fast=slow;
        while(k){
            fast=fast->next;
            k--;
        }
        slow=slow->next;        //模拟一遍会发现slow指针需要先走一步
        while(fast->next){
            slow=slow->next;
            fast=fast->next;
        }
        return slow;
    }
};
posted on 2023-07-21 21:06  孜孜不倦fly  阅读(20)  评论(0)    收藏  举报