题目描述
代码实现
/*
输入一个链表,输出该链表中倒数第k个结点
思路:设置两个指针,slow,fast,先让fast走k步,然后再一起走直到fast为NULL时,slow即为倒数第k个节点
*/
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* FinkKthToTail(struct ListNode* pListHead, int k)
{
struct ListNode *slow, *fast;
slow = fast = pListHead;
// 先让fast走k步
while (k--)
{
if (fast == NULL)
{
return NULL;
}
fast = fast->next;
}
// slow和fast一起走,直到fast为NULL
while (fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}