- 题目:输入一个链表,输出该链表中倒数第k个结点。
- idea:两个指针,第一个先走k步
- code:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* head, unsigned int k) {
if (k == 0 || !head) return 0;
ListNode* p = head;
int i = 0;
while(p){
if (i < k){
p = p->next;
i++;
}
else
break;
}
if (i<k) return 0;
ListNode *res = head;
while(p){
p = p->next;
res = res->next;
}
return res;
}
};