思路:
链表的题目,要么内存逻辑代替法、要么快慢指针、要么先后指针,要么多指针,本题可以用先后指针(一个先出发,一个后出发)
代码:
/*
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 NULL;
ListNode *forward=pListHead;
ListNode *target=pListHead;
for(int i=0;i<k;++i){
if(forward==NULL)
return NULL;
forward=forward->next;
}
while(forward){
forward=forward->next;
target=target->next;
}
return target;
}
};
网友评论