解题思路:
(1)首先求出链表的总个数,再从前往后判断
/*
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* p = pListHead;
unsigned count = 0;//总个数
while(pListHead) {
count++;
pListHead = pListHead->next;
}
if (count<k) return NULL;
unsigned j = 0;
while(j<count-k) {
p = p->next;
j++;
}
return p;
}
};
(2) C++ 保存中间指针,最后按下标输出
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
vector<ListNode*> p;
unsigned count = 0;//总个数
while(pListHead) {
p.push_back(pListHead);
count++;
pListHead = pListHead->next;
}
if (count<k) return NULL;
return p[count-k];
}
};
(3)快慢指针
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 front = pListHead,back = pListHead;
for (int i=0;i<k;i++) {
if (front) front = front->next;
else if (i==k) return back;
else return NULL;
}
while(front) {
front=front->next;
back=back->next;
}
return back;
}
};