问题:输入一个链表,输出该链表中倒数第k个结点。
思路:定义两个指针,一快一慢,快的先走k步;
具体代码:(C++)
struct ListNode
{
int val;
ListNode* next;
ListNode(int x):val(x),next(nullptr){}
};
class Solution
{
public:
ListNode* FindKthNodeToTail(ListNode* pHead, unsigned int k)
{
if(pHead == nullptr || k== 0)
retrun nullptr;
ListNode* pAhead = pHead;
ListNode* pAfter = pHead;
for(int i=0;i<k;i++) //快指针领先k步
{
if(pAhead->next != nullptr)
{
pAhead = pAhead->next;
}
else
return nullptr; //链表总长度不到k
}
while(pAhead->next != nullptr)
{
pAhead = pAhead->next;
pAfter = pAfter->next;
}
return pAfter;
}
};