xAdvitya
xAdvitya

Reputation: 129

program compiling but not running c++

Its not an homework assignment I'm coding binary tree with queue but the program is not working its compiling but not printing anything

Code for queue

#include<bits/stdc++.h>
using namespace std;

class treeNode{
    public:
    treeNode *lchild;
    int data;
    treeNode *rchild;
};

class circularQueue{

    int f;//front
    int r;//rear
    int s;//back
    treeNode **Q; 
    public:
    circularQueue(int size){
        this->f=0;
        this->r=0;
        this->s = size;
        *Q = new treeNode;
    }

    void enqueue(treeNode *val);
    treeNode* deque();
    int isEmpty();
};

void circularQueue :: enqueue(treeNode *val){

    if((r+1)%s == f){
        cout<<"Queue is full\n";
    }
    else{
        r = (r+1) % s;
        Q[r] = val;
    }

}

treeNode* circularQueue :: deque(){

    treeNode *x = NULL;

    if(f == r){
        cout<<"Queue is empty\n";
    }
    else{
        f = (f+1)%s;
        x = Q[f];
    }
    return x;
}

int circularQueue::isEmpty(){
    return f==r;
}

code for tree creation

#include<bits/stdc++.h>
#include "queue.h"
using namespace std;

treeNode *root = NULL;
void create(){
    treeNode *p,*t;
    int x;
    circularQueue q(100);
    std::cin.ignore(INT_MAX);
    cout<<"enter root value\n";
    cin>>x;

    root->data = x;
    root->lchild=root->rchild = NULL;

    q.enqueue(root);

    while(!q.isEmpty()){
        p = q.deque();
        cout<<"enter value of lchild"<<p->data<<endl;
        cin>>x;
        if(x!=-1){
            t = new treeNode();
            t->data = x;
            t->lchild->rchild = NULL;
            p->lchild = t;
            q.enqueue(t);
        }

    }
 cout<<"enter value of rchild"<<p->data<<endl;
        cin>>x;
        if(x!=-1){
            t = new treeNode();
            t->data = x;
            t->rchild->rchild = NULL;
            p->lchild = t;
            q.enqueue(t);
        }

}

void preorder(treeNode *p){
    if(p){
        cout<<p->data<<" ";
        preorder(p->lchild);
        preorder(p->rchild);
    }

}
int main(){

    create();
    preorder(root);

}

Upvotes: 1

Views: 51

Answers (1)

Rumburak
Rumburak

Reputation: 3571

In this line

*Q = new treeNode;

you are de-referencing an uninitialized pointer (undefined behavior). I wonder why you are using a pointer to a pointer? Seems unnecessary.

If the undefined behavior does not lead to a crash, your program will seemingly stop here:

std::cin.ignore(INT_MAX);

You are essentially waiting until STDIN ends.

Hope this helps!

Upvotes: 1

Related Questions