1 回答

TA貢獻1831條經驗 獲得超10個贊
如你所想,問題出在free上
本質是入棧,出棧的函數太復雜,適應性不強,容易出錯
比如S=Push_LS(S, p);這句沒必要,直接Push_LS(S, p);
可以用下面pop,push函數替換
int push(linkstack *s,ElemType *x)//入棧操作,將x的數據元素插入棧s中,使x成為新的棧頂元素
{
linkstack *p,*q;
q=s;
p=(linkstack *)malloc(sizeof(linkstack));
if(!p)exit(-1);
p->stack=*x;
p->next=NULL;
while(q->next)
q=q->next;
q->next=p;
return 1;
}
/////////////////////////////////////////////////
//因為非遞歸遍歷算法 調用的棧不需要 全部出棧
//進棧的鏈表實現的 真正算法為
// q->stack=*x;
// q->next=S->next;
// S->next=q;
////////////////////////////////////////////////
int pop(linkstack *s,ElemType *e)//出棧操作,先將棧s的棧頂結點的值送到e所指向的內存單元,然后刪除棧頂結點
{
linkstack *p,*q;
p=s;
if(s->next==NULL)return 0;
while(p->next)
{
q=p;
p=p->next;
}
q->next=NULL;
*e=p->stack;
free(p);
return 1;
}
- 1 回答
- 0 關注
- 130 瀏覽
添加回答
舉報