/*
在鏈表中找倒數第k個元素
考慮的問題 :
鏈表可能會空,
K可能會很大,超過鏈表的個數,
鏈表的結點個數超過int 表示的範圍
*/
LinkNode *findTheLastKInlist (LinkNode *head,int k)
{
LinkNode *tem=NULL;
tem=head;
LinkNode *pLastK=NULL;//the last kth node pointer int list
int count=0;
if(k<=0)
return NULL;
while(tem!=NULL)
{
tem=tem->next;
if(pLastK==NULL) //鏈表結點樹很大時,可能count會溢出,所以把count語句放在判斷語句內
{
count++;
}
if(count>=k) /*當遍歷指針從頭結點開始移動了k-1個結點,pLastK 從頭結點開始,隨着遍歷指針移動*/
{
if(pLastK==NULL)
pLastK=head;
else
{
pLastK=pLastK->next;
}
}
}
return pLastK;
}
鏈表中倒數第K個元素,
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.