c++ - 我正在尝试使用队列实现 bfs。有人可以帮我找到错误吗?

标签 c++ c algorithm data-structures

下面的代码在显示两个节点后给出了运行时错误。 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/

相关文章:

c++ - 使用 scanf() 进行动态分配

algorithm - 理解调度以最小化迟到问题

python - 在python中分配数组(列表)算法排列

c++ - 初始化 const 指针 - C++ 中的初始化列表

c++ - 从字符串中删除 char 的第一个和最后一个实例

c++ - qt slider 问题c++

c - 当我测试书 'Introduction to Algorithms' 中的堆排序代码时出现段错误 : 11,

c - 如何在 c 中打印一个 unsigned int*?

ruby-on-rails - 数组连接函数 - Ruby on Rails

C++ 动态绑定(bind)