// 查找鏈表的倒數第K個結點ide
示意圖:spa
PSListNode FindLastKNode(PSListNode pHead, int K )blog
{get
PSListNode pFast = pHead ;it
PSListNode pSlow = pHead ;io
if (pHead == NULL || K <= 0)ast
{class
return NULL ;List
}im
while (--K )
{
if (pFast == NULL )
{
return NULL ;
}
pFast = pFast->pNext;
}
while (pFast->pNext)
{
pSlow = pSlow->pNext;
pFast = pFast->pNext;
}
return pSlow;
}
建議:若是理解不清楚,必定要畫個圖,看着圖寫代碼會容易不少,思路也會清晰