输入一个链表,输出该链表中倒数第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) {
//快慢指针,转化为正数第几个
unsigned int temp = k;
ListNode* fast = pListHead;
if (temp == 0)
return nullptr;
//先走到正数第K+1个
while (temp--) {
if (fast)
fast = fast->next;
else
return nullptr;
}
//快指针走到尾,慢指针就走到了倒数第K个
ListNode* slow = pListHead;
while (fast) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};