下面的代码在显示两个节点后给出了运行时错误。 display()
或 push()
肯定有问题; pop()
和 insert()
函数运行良好。 (我单独查了一下。)我们插入节点,直到他们的 child 的值不等于-1。
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
typedef struct node list;
list queue[20];
int back=-1,front=0;
void push(list x)
{
if(back-front==1)
printf("queue full");
else
{
if(back==19)
back=1;
else
back++;
queue[back]=x;
}
}
list pop()
{
/*if(back-front==1)
printf("queue empty");
else
{*/
list x=queue[front];
if(front==19)
front=1;
else
front++;
return x;
//}
}
void insert(list *ptr,int x)
{
ptr->data=x;
int p,q;
scanf("%d",&p);
scanf("%d",&q);
if(p!=-1)
{
ptr->left=(list *)malloc(sizeof(list));
insert(ptr->left,p);
}
else
ptr->left==NULL;
if(q!=-1)
{
ptr->right=(list *)malloc(sizeof(list));
insert(ptr->right,q);
}
else
ptr->right==NULL;
}
void display(list *ptr)
{
push(*ptr);
/*printf("%d",queue[back].data);
printf("%d",(queue[back].left)->data);
printf("%d",(queue[back].right)->data);*/
while(front<=back)
{
list x=pop();
printf("%d\n",x.data);
if(x.left!=NULL)
push(*(x.left));
if(x.right!=NULL)
push(*(x.right));
}
}
int main()
{
int x;
scanf("%d",&x);
list *head=(list *)malloc(sizeof(list));
insert(head,x);
display(head);
return 0;
}
最佳答案
您的insert
不没问题。再次检查。
void insert(list *ptr,int x)
{
ptr->data=x;
int p,q;
scanf("%d",&p);
scanf("%d",&q);
if(p!=-1)
{
ptr->left=(list *)malloc(sizeof(list));
insert(ptr->left,p);
}
else
ptr->left==NULL; // <<== should be =, not ==
if(q!=-1)
{
ptr->right=(list *)malloc(sizeof(list));
insert(ptr->right,q);
}
else
ptr->right==NULL; // <<== should be =, not ==
}
注意:到目前为止,这不是唯一的 问题,但这是一个良好的开端。和 don't cast malloc()
in C .
关于c++ - 我正在尝试使用队列实现 bfs。有人可以帮我找到错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18495649/