3.11编写查找单链表某元素的程序,分别用递归和非递归方法实现,并比较运行时间。链表达到多大才会令递归程序崩溃?
递归压栈会浪费大量额外空间与时间,因此非递归程序会比递归程序运行时间短。
链表长度约5000时递归查找即崩溃,而迭代可在1000000长度的链表下正确运行。
//非递归方法实现
Position Find_nonrecursion(Elmenttype x,List L)
{
Position p;
p=First(L);
while(p!=NULL&&p->Elmentment!=x)
p=p->next;
return p;
}
//递归方法实现
Position Find_recursion(Elmenttype x,List L)
{
Position p;
p=First(L);
if(p!=NULL&&p->Elmentment!=x)
Find_recursion(x,p);
else
return p;
}
3.12反转单链表 时间复杂度O(n)
a.非递归过程
头插法
//无头节点且不空
List InverseList(List L)
{
List last;
last=MakeEmpty(NULL);
Position pos,nextpos,lastpos;
pos=First(L);
nextpos=pos->pos;
lastpos=First(lastpos);
while(pos!=NULL)
{
L->next=pos->next;
pos->next=lastpos;
lastpos=pos;
pos=L;
}
return lastpos;
}
b.使用常数附加空间
原地反转法
//表无头节点且不是空表
List InverseList(List L)
{
Position Previouspos,Currentpos,Nextpos;
Previouspos=NULL;
Currentpos=L;
Nextpos=L->next;
while(Nextpos!=null)
{
Currentpos->next=Previouspos;
Previouspos=Currentpos;
Currentpos=Nextpos;
Nextpos=Nextpos->next;
}
Currentpos=Currentpos->next;
return Currentpos;
}