PSListNode FindLastKNode(PSListNode pHead, int K)
{
if ((NULL == pHead) || (K <= 0))
{
return NULL;
}
else
{
PSListNode pFast = pHead;
PSListNode pSlow = pHead;
//利用快慢指针,让快指针先走K-1步,然后两指针同时走,直到快指针指向的下一个结点为空为止
while (--K)
{
pFast = pFast->pNextNode;
if (NULL == pFast)
{
return NULL;
}
}
while (NULL != pFast->pNextNode)
{
pFast = pFast->pNextNode;
pSlow = pSlow->pNextNode;
}
return pSlow;
}
}
查找单链表的倒数第k个节点,要求只能遍历一次链表(C语言)
最新推荐文章于 2021-05-21 22:34:43 发布