單鏈表中查找倒數第K個節點

// 查找鏈表的倒數第K個結點ide

示意圖:spa

wKiom1cIpvrTNh1hAABdYE4x9hg680.png


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;

}

建議:若是理解不清楚,必定要畫個圖,看着圖寫代碼會容易不少,思路也會清晰

相關文章
相關標籤/搜索