void DeleteLastKNode(pList plist, int k)
{
//1.找到倒数第k个结点
int count = 0;
pNode pFast = plist;
pNode pSlow = plist;
pNode pPre = 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;
count++;
//由于要删除,则必须用一个指针来标记待删结点的前一个结点
if (count > 1)//pSlow比pPre多走一步
{
pPre = pPre->next;
}
}
//2.删除结点(第一个结点/非第一个结点)
if (plist->next == NULL)//如果是第一个结点
{
plist = plist->next;
free(pSlow);
pSlow = NULL;
}
else
{
pPre->next = pSlow->next;
free(pSlow);
pSlow = NULL;
}
}