明明不止一次看到这个算法还是在每次看到的时候恍然大悟,我也是绝了,每次都用暴力。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
ListNode *p=pHead;
ListNode *q=pHead;
int len=0;
while(p!=NULL){
p=p->next;
len++;
}
if(len<k) return nullptr;
else{
for(int i=0;i<len-k;i++)
q=q->next;
}
return q;
}
};
双指针,一个先走k步,然后两个一起走,直到前面那个到最后。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
ListNode *p=pHead;
ListNode *q=pHead;
if(nullptr==pHead||k<=0)
return nullptr;
while(nullptr!=p&&k){
k--;
p=p->next;
}
if(k)
return nullptr;
while(p){
p=p->next;
q=q->next;
}
return q;
}
};