题目:

/**
* 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;
}
};
浙公网安备 33010602011771号