I am trying to implement bfs with queue.Can anyone help me in finding the
error?
//The below code is giving run time error after displaying two nodes.There
must be some problem in display function,or push,pop function,insert
function is working fine.I have checked it seperatly.We insert nodes till
the value of their child is not equal -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;
}
No comments:
Post a Comment