注册 登录
编程论坛 C++教室

为什么?为什么?为什么?析构函数不能正常运行?(二叉树部分习题)

蓝颜 发布于 2011-10-28 23:04, 708 次点击
#include<iostream>
#include<string>
using namespace std;
//*******************************************************************
class Node
{
public:
        string info;
        int num;//第几个创建
        Node *next;//用来连接新建的节点
        Node *left;//左子女
        Node *right;//右子女
public:
    Node(string inf,int nu=0)
    {
        info=inf;
        num=nu;
        next=left=right=NULL;
    }
    ~Node(){cout<<"~Node()"<<endl;}
};
//*****************************************************************
class binaryTree
{
    private:
        Node *root;//根节点
    public:
        binaryTree(Node *root=NULL){this->root=root;}//构造函数
        ~binaryTree();
        void insert();                       
};
//*****************************************************************************
binaryTree::~binaryTree()//析构函数
{
    cout<<"析构函数"<<endl;
    for(Node *p=root;p!=NULL;)
    {
        root=p->next;
        delete []p;
        p=root;
    }
}
void binaryTree::insert()//插入函数
{
    cout<<"输入要插入的节点的字符串(stop结束):";
    string str;
    cin>>str;
    Node *temp,*p;//temp用来指向新生成的指针
    int number=0;
    while(str!="stop")
    {
        number++;
        if(root!=NULL)
        {
            temp->next=new Node(str,number);
            temp=temp->next;//temp用来指向新生成的指针
            for(int i=1;i<number/2;p=p->next,i++);//用循环让P指向temp的父节点
            number%2==0?p->left=temp:p->right=temp;
            p=root;
        }
        else
            p=temp=root=new Node(str,number);
        cout<<"输入要插入的节点的字符串(stop结束):";
        cin>>str;
    }
}
void main()
{
    binaryTree tree;
    tree.insert();
}
2 回复
#2
YueWuSS2011-10-29 06:57
//析构函数delete语句错误
//delete []p; 释放数组
//改为如下的函数
//!OK
binaryTree::~binaryTree()//析构函数
 {
     cout<<"析构函数"<<endl;
     for(Node *p=root;p!=NULL;)
     {
         root=p->next;
         delete p;
         p=root;
     }
 }
#3
蓝颜2011-10-29 08:35
刚刚尝试,你说的完全正确!!!
1