| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 708 人关注过本帖
标题:为什么?为什么?为什么?析构函数不能正常运行?(二叉树部分习题)
只看楼主 加入收藏
蓝颜
Rank: 1
来 自:陕西西安
等 级:新手上路
帖 子:7
专家分:0
注 册:2011-6-15
结帖率:0
收藏
 问题点数:0 回复次数:2 
为什么?为什么?为什么?析构函数不能正常运行?(二叉树部分习题)
#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();
}
搜索更多相关主题的帖子: include public 二叉树 class right 
2011-10-28 23:04
YueWuSS
Rank: 2
等 级:论坛游民
帖 子:15
专家分:96
注 册:2011-10-29
收藏
得分:0 
//析构函数delete语句错误
//delete []p; 释放数组
//改为如下的函数
//!OK
binaryTree::~binaryTree()//析构函数
 {
     cout<<"析构函数"<<endl;
     for(Node *p=root;p!=NULL;)
     {
         root=p->next;
         delete p;
         p=root;
     }
 }
2011-10-29 06:57
蓝颜
Rank: 1
来 自:陕西西安
等 级:新手上路
帖 子:7
专家分:0
注 册:2011-6-15
收藏
得分:0 
刚刚尝试,你说的完全正确!!!
2011-10-29 08:35
快速回复:为什么?为什么?为什么?析构函数不能正常运行?(二叉树部分习题)
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014485 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved