O
问题
实现
思路
首先这种题目是有固定的解法的, 由于链表长度是没法直接get的, 倒数我们更不知道,那么可以考虑用快慢指针
一个往前先走n, 然后两个同时走,当快指针走到结束,慢指针刚好到了倒数k.
- define fast slow pointer
- for i<k
-
- when fast= NULL break;
-
-
- fast = fast->next;
-
- while§
-
- fast++
-
- slow ++
- return
总结与反思
- while(fast) 相当于为空的那一步就不走了, 循环条件到底是统一用fast.next还是fast要仔细思考一下。 这里我决定用fast , 这相当于 < size() , 而 fast.next 相当于<= size-1.
代码实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
auto fast = pListHead;
auto slow = pListHead;
for(unsigned int i= 0 ;i<k;i++){
if(!fast) return NULL;
else fast = fast->next;
}
while(fast){
fast = fast->next;
slow = slow->next;
}
return slow;
}
};