class
Solution {
public
:
ListNode* FindKthToTail(ListNode* p, unsigned
int
k) {
//if(!p) return nullptr;
auto p1=p;
for
(
int
i=0;i!=k;++i)
if
(!p1)
return
nullptr;
else
p1=p1->next;
while
(p1){
p1=p1->next;
p=p->next;
}
return
p;
}
};
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode* first = pListHead;
ListNode* second = pListHead;
if(first == nullptr)
return nullptr;
for(int i =0 ;i <k-1;i++){ //这里走k-1步,为什么呢? 因为第k步就要和second一起走
if(first->next != nullptr)
first = first->next;
else
return nullptr;
}
while(first->next != nullptr){
first = first->next;
second = second ->next;
}
return second;
}
};
原文:https://www.cnblogs.com/yl1995/p/12939985.html