问题描述
- 先序建的树,中序遍历,为啥在Push处会中断运行啊
-
#include #include #include #define S_SIZE 100 #define STACKINCREMENT 10 typedef struct BiTNode { char data; struct BiTNode *lchild, *rchild; }BiTNode,*BiTree; typedef BiTNode ElemType; typedef struct { ElemType *base; ElemType *top; int stacksize; }SqStack; BiTree CreateBiTree(BiTree T) { char ch; scanf_s("%c",&ch); if (ch == ' ') T = NULL; else { T = (BiTree)malloc(sizeof(BiTNode)); T->data = ch; T->lchild=CreateBiTree(T->lchild); T->rchild=CreateBiTree(T->rchild); } return T; } void InitStack(SqStack *L) { L->base = (ElemType *)malloc(sizeof(S_SIZE * sizeof(char))); L->top = L->base; L->stacksize = S_SIZE;
}
void Push(SqStack *L, ElemType *e)
{
if (L->top - L->base >= L->stacksize)
{//栈满,追加存储空间
L->base = (ElemType *)realloc(L->base, (L->stacksize + STACKINCREMENT)*sizeof(ElemType));
L->top = L->base + L->stacksize;
L->stacksize += STACKINCREMENT;
}
*L->top++= *e;运行到这会中断
}
void Pop(SqStack *L, ElemType *e)
{
if (L->top != L->base)
{
e = --L->top;
}}
int StackEmpty(SqStack *L)
{
if (L->top == L->base)
return 1;
else
return 0;
}int InOrderTraverse(BiTNode *T)
{
SqStack *L;
L = (SqStack *)malloc(sizeof(SqStack));
BiTree p;
InitStack(L); p = T;
while (p || !StackEmpty(L))
{
if (p) { Push(L, p); p = p->lchild; } // 非空指针进栈,继续左进
else { // 上层指针退栈,访问其所指结点,再向右进
Pop(L, p);
if (!printf("%c",p->data)) return 1 ;
p = p->rchild;
}
}
return 0;
}void main()
{
BiTree T;
T = (BiTree)malloc(sizeof(BiTNode));
CreateBiTree(T);
InOrderTraverse(T);
printf("WSQ");
getchar();}
解决方案
晕这么长,还真不好看。建议楼主学会调试程序,设断点、单步执行等手段。
解决方案二:
以后楼主发程序可以用代码段发 还是先学会调试吧