【发布时间】:2018-01-30 22:08:23
【问题描述】:
这是我的迭代中序遍历函数。 但是当我执行它时,我遇到了分段错误。 我正在使用堆栈进行遍历。在给定的程序中,我还有一个用于中序遍历的递归函数,以检查我的 create() 函数是否正常工作。
我将节点推送到堆栈并移动到节点的左侧,然后我从堆栈中弹出节点并打印它并通过执行向右移动
root=root->rlink.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *llink;
struct node *rlink;
}Node;
typedef struct Stack
{
Node *a[10];
int top;
}stack;
void push(stack *s,Node *root)
{
if(s->top==9)
printf("FULL");
else
{
s->top++;
s->a[s->top]=root;
}
}
Node *pop(stack *s)
{
if(s->top==-1)
printf("Empty");
return s->a[s->top--];
}
void inorder(Node *root)
{
stack s;
s.top=-1;
int flag=1;
while(flag)
{
if(s.top!=9)
{
push(&s,root);
root=root->llink;
}
else{
if(s.top!=-1)
{
root=pop(&s);
printf("%d",root->data);
root=root->rlink;
}
else
flag=0;
}
}
}
void inor(Node *root)
{
if(root!=NULL)
{
inor(root->llink);
printf("%d",root->data);
inor(root->rlink);
}
}
Node *create(Node *root,int key)
{
if(root==NULL)
{
root=(Node *)malloc(sizeof(Node));
root->data=key;
root->rlink=root->llink=NULL;
}
else
{
if(key>root->data)
{
root->rlink=create(root->rlink,key);
}
else if(key<root->data)
{
root->llink=create(root->llink,key);
}
}
return root;
}
int main()
{
Node *h=NULL;
h=create(h,5);
h=create(h,1);
h=create(h,3);
h=create(h,8);
h=create(h,12);
h=create(h,51);
inorder(h);
//inor(h);
}
【问题讨论】:
-
您是否使用调试器立即找出导致段错误的行并跟踪程序的执行?
-
确保您使用换行符终止诊断打印消息(或使用
fflush(stdout);) - 否则,如果代码崩溃,您可能永远看不到消息,从而给您错误的崩溃发生位置的印象。 -
@kaylum 是的,我做到了,但我想不通
-
@JonathanLeffler Oaky 我会这样做的
-
好的,那么至少告诉我们哪条线触发了段错误。调试器会立即为您提供。
标签: c data-structures binary-tree binary-search-tree