【问题标题】:program compiling but not running c++程序编译但不运行 c++
【发布时间】:2020-04-25 07:52:15
【问题描述】:

这不是家庭作业 我正在用队列编码二叉树,但程序没有编译但没有打印任何东西

  • 我尝试清除 cin 缓冲区,但问题仍然存在
  • 我使用 vscode 和 sublime text 运行代码
  • 我正在使用 cpp14
  • 制作exe文件 -其他程序正常运行

队列代码

#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;
}

树创建代码

#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);

}

【问题讨论】:

标签: c++ data-structures tree binary-tree dsa


【解决方案1】:

在这一行

*Q = new treeNode;

您正在取消引用未初始化的指针(未定义的行为)。我想知道你为什么使用指向指针的指针?似乎没有必要。

如果未定义的行为不会导致崩溃,您的程序似乎会停在这里:

std::cin.ignore(INT_MAX);

您实际上是在等待 STDIN 结束。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多