我想用链表来实现二叉树,为此我也用链表来实现堆栈和队列
堆栈和队列我还使用了链表
在我的代码中没有语法错误,它的编译成功,但运行代码的时间它说分割错误
请有人发现我的错误并修复它…
在下面的代码中,我分成了三个单独的文件:-第一个文件是class file(用于定义所有类,如堆栈,队列,树)
第二个文件是函数文件,其中所有的函数体都在每个类中声明。
第三个文件是主文件。
第一档(类别H)
#ifndef CLASS
#define CLASS
#include <iostream>
using namespace std;
//tree class (start)
class Node
{
public:
Node *lchild;
int data;
Node *rchild;
};
class tree
{
private:
Node *root = NULL;
public:
tree();
void preorder();
};
//tree class (end)...
//queue class (start)
class Q_Node
{
public:
Node *data;
Q_Node *next;
};
class Queue
{
private:
Q_Node *first, *reare;
public:
Queue(){first = reare = new Q_Node;}
void enqueue(Node *x);
Node * dequeue();
void display();
int isEmpty();
};
//tree class (end)...
//stack class (start)
class S_Node
{
public:
Node *data;
S_Node *next;
};
class Stack
{
private:
S_Node *top;
public:
Stack(){top = NULL;}
void push(Node *x);
Node * pop();
int isEmpty();
};
//stack class (end)...
#endif
第二个文件(functions.cpp)
#include "classes.h"
//functions of queue class
void Queue::enqueue(Node *x){
Q_Node *t;
t = new Q_Node;
if(!t)
cout<<"Queue is full"<<endl;
else{
t->data = x;
t->next = NULL;
if(!first) first = t;
if(reare) reare->next = t;
reare = t;
}
}
Node * Queue::dequeue(){
Q_Node *t;
Node *x = NULL;
if(!first)
cout<<"Queue is empty"<<endl;
else{
t = first;
x = t->data;
first = first->next;
delete t;
}
return x;
}
int Queue::isEmpty(){
if(first == reare)
return 1;
return 0;
}
//functions of stack class
void Stack::push(Node *x){
S_Node *t;
t = new S_Node;
if(!t)
cout<<"Stack overflow"<<endl;
else{
t->data = x;
t->next = top;
top = t;
}
}
Node * Stack::pop(){
Node *x = NULL;
S_Node *t;
if(!top){
cout<<"Stack is empty"<<endl;
}else{
x = top->data;
t = top;
top = top->next;
delete t;
}
return x;
}
int Stack::isEmpty(){
if(top == NULL)
return 1;
return 0;
}
//functions of tree class
tree::tree(){
int x;
Node *t, *p;
Queue q;
cout<<"Enter root value"; cin>>x;
root = new Node;
root->data = x;
root->lchild=root->rchild = NULL;
q.enqueue(root);
while(!q.isEmpty()){
p = q.dequeue();
cout<<"Enter left child value of "<<p->data<<": "; cin>>x;
if(x != 1){
t = new Node;
t->data = x;
t->lchild = t->rchild = NULL;
p->lchild = t;
q.enqueue(t);
}
cout<<"Enter right child value of "<<p->data<<": "; cin>>x;
if(x != 1){
t = new Node;
t->data = x;
t->lchild = t->rchild = NULL;
p->rchild = t;
q.enqueue(t);
}
}
}
void tree::preorder(){
Node *p = root;
Stack s;
while(p || !s.isEmpty()){
if(p){
cout<<p->data<<" ";
s.push(p);
p = p->lchild;
}
else{
p = s.pop();
p = p->rchild;
}
}
}
第三个文件(main.cpp)
#include <iostream>
#include "classes.h"
using namespace std;
int main(int argc, char const *argv[])
{
tree t;
t.preorder();
return 0;
}
对于
顺便说一句:注意
Q_Node *t;
t = new Q_Node;
if(!t)
cout<<"Queue is full"<<endl;
else ...
不会产生预期的结果。如果无法分配更多内存,则抛出
#include <new>
...
Q_Node *t;
t = new(std::nothrow) Q_Node;
if(!t)
cout<<"Queue is full"<<endl;
else ...