剑指OFFER 链表中倒数第K个结点
思路
设置两个间隔为K个结点的指针,他们同步前进,后结点到达NULL的时候,说明前结点就是倒数第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) {
ListNode* node = pListHead;
ListNode* node_rec = node;
int count= 1;
while(node != NULL)
{
if(count>k)node_rec = node_rec->next;
count++;
node = node->next;
}
if(count<=k){
return NULL;
}else{
return node_rec;
}
}
};