1. 程式人生 > >查詢單鏈表的倒數第k個結點,要求只能遍歷一次連結串列

查詢單鏈表的倒數第k個結點,要求只能遍歷一次連結串列

pNode FindLastKNode(pList plist, int k)
{
	pNode pFast = plist;
	pNode pSlow = plist;
	if (plist == NULL || k <= 0)
	{
		return NULL;
	}
	while (k--)//pFast先走k步
	{
		if (pFast == NULL)//k大於連結串列中結點的個數
		{
			return NULL;
		}
		pFast = pFast->next;
	}
	while (pFast)//兩個指標同時朝後走
	{
		pFast = pFast->next;
		pSlow = pSlow->next;
	}
	return pSlow;
}