力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *fast = head ,*slow=head;
for (int i = 0;i < k;i++) {
if(nullptr == fast) return nullptr;
fast=fast->next;
}
while(fast!=nullptr) {
fast=fast->next;
slow=slow->next;
}
return slow;
}
};
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public:
int kthToLast(ListNode* head, int k) {
ListNode*fast=head,*slow=head;
for(int i=0;i<k;i++) fast=fast->next;
while(fast)
{
fast=fast->next;
slow=slow->next;
}
return slow->val;
}
};