题目如下
解题思路
vector存下链表,然后用小标输出
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode *tail=head;
vector<ListNode*>res;
while(tail!=NULL){
res.push_back(tail);
tail=tail->next;
}
return res[res.size()-k];
}
};
快慢指针
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
if(!head || k == 0) return nullptr;
ListNode *fast = head, *slow = head;
for(int i=1; i<=k-1; ++i){
if(fast -> next) fast = fast -> next;
else return nullptr;
}
while(fast -> next){
fast = fast -> next;
slow = slow -> next;
}
return slow;
}
};