设置两个指针,kth,end,kth初始化为NULL,当链表的长度小于k值时,返回NULL,表示没有这个节点。当该链表为空时,返回pListHead,k的数值类型为unsigned int,取值可能为0时,当取0时,不成立,返回NULL。
设置一个计数器count,累加count的值,当count=k时,end指向第k个节点,令kth指向pListHead,pListHead与end之间的距离为k,依次累加kth和end,当end指向尾节点时,kth指向倒数第k个节点
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution{
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k)
{
if (pListHead==NULL)
return pListHead;
if(k==0)
return NULL;
ListNode* kth=NULL,*end=pListHead;
int count=0;
while(end!=NULL)
{
count++;
if(count==k)
kth=pListHead;
else if(count>k)
kth=kth->next;
end=end->next;
}
return kth;
}
};
换一种写法
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode *fast = pListHead, *slow = pListHead;
for (int i = 1; i <= k; i++) {
if(fast == NULL)
return NULL;
fast = fast->next;
}
while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};