先序非递归输出的问题【求助】
#include<stdio.h>#include<stdlib.h>
typedef struct nodf //树的结点结构体
{
int data;
struct nodf *lchild,*rchild;
}bitree;
bitree *Q[20];//定义一个指向bitree的指针数组
typedef struct node
{
bitree *s;
struct node *next;
}linkstack;
linkstack *top=NULL;//空栈
linkstack *push(linkstack *top,bitree *x)//进栈
{
linkstack *p;
p=(linkstack*)malloc(sizeof(linkstack));
p->s=x;
p->next=top;
top=p;
return top;
}
linkstack *pop(linkstack *top)//出栈
{
linkstack *p;
p=top;
top=top->next;
free(p);
return top;
}
int empty(linkstack *s)
{
if(s->next==NULL)
return 1;
else
return 0;
}
bitree *creatree()
{
int ch;
int front=1,rear=0;
bitree *root,*s;
root=NULL;
scanf("%d",&ch);
while(ch!=-1)
{
s=NULL;
if(ch!=0)
{
s=(bitree*)malloc(sizeof(bitree));
s->data=ch;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1) root=s;
else
{
if(s!=NULL&&Q[front]!=NULL)
{
if(rear%2==0) Q[front]->lchild=s;
else Q[front]->rchild=s;
if(rear%2==1) front++;
}
}
scanf("%d",&ch);
}
return root;
}
void pri(bitree *s,linkstack *top)//先序排列 非递归
{
linkstack *acc;
while(s!=NULL||(empty(top)==0))
{
while(s!=NULL)
{
printf("%d ",s->data);
top=push(top,s);
s=s->lchild;
}
if(s==NULL)
{
acc=pop(top); //这里的出栈并不能使free里的实参回收,导致不断地循环 可是我想不出应该怎么去修改
s=acc->s->rchild;
}
}
}
int main()
{
bitree *tree=creatree();
pri(tree,top);
return 0;
}