1.题目
输入一个链表,输出该链表中倒数第k个结点。
2.思路
ahead先走 (k - 1)步 (因为倒数第k个节点需要 k - 1步到达尾节点)
ahead behind 同时开始, ahead走到尾节点时,behind走到倒数第k个节点。
相对位置:
*-*-*-*-*-*-*-*-*-*
|k-1|
*-*-*-*-*-*-*-*-*-*
|k-1|
3.实现
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead == nullptr || k <= 0)
return nullptr;
ListNode* ahead = pListHead;
for(int i = 1; i <= k - 1; i++)
{
ahead = ahead->next;
if(ahead == nullptr)
return nullptr; //节点数不足k个
}
ListNode* behind = pListHead;
while(ahead->next != nullptr)
{
ahead = ahead->next;
behind = behind->next;
}
return behind;
}
};