链表中倒数第K个元素,

/*
在链表中找倒数第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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章