这几天的难点有:树形结构删除节点,c字符串的用法,堆栈空间
还是c/c++基础差了些,我要继续努力
有个程序很有意思:
#include <iostream>
#include <string>
using namespace std;
struct node
{
node(const string& name, node *fc = 0, node* ns = 0)
: name(name), firstChild(fc), nextSibling(ns)
{
}
~node()
{
}
node *firstChild;
node *nextSibling;
string name;
};
void delete(node* root)
{
if (NULL != root)
{
deleteAll(root->firstChild);
}
}
void deleteAll(node *& root)
{
if (NULL != root)
{
deleteAll(root->firstChild);
deleteAll(root->nextSibling);
delete root;
root = NULL;
}
}
void print(node *root, int tab)
{
if (NULL != root)
{
for (int i = 0; i < tab; ++i)
{
cout << ' ';
}
cout << root->name << endl;
print(root->firstChild, tab + 4);
print(root->nextSibling, tab);
}
}
int main()
{
node *root = new node("root");
node *c1 = new node("child1");
node *c2 = new node("child2");
node *c3 = new node("child3");
c1->nextSibling = c2;
c2->nextSibling = c3;
root->firstChild = c1;
node *c11 = new node("child11");
c1->firstChild = c11;
node *c12 = new node("child12");
c11->nextSibling = c12;
node *c21 = new node("child21");
c2->firstChild = c21;
node *c22 = new node("child22");
c21->nextSibling = c22;
c11->firstChild = new node("child111");
print(root, 0);
/////////////////////////////////////////
// 这个地方如果改成 deleteAll( c1 );便会 出内存错误,最后才知道原来是堆栈问题。恩,不错
deleteAll(root->firstChild);
//print(root, 0);
return 0;
}