|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
//C++ programming language chapter 7 exercise 7
#include <iostream>
#include <string>
using namespace std;
typedef struct Tnode {
string word;
int count;
Tnode *left;
Tnode *right;
};
Tnode* new_Tnode(string const &word) {
Tnode *node = new Tnode;
node->word = word;
node->count = 1;
node->left = node->right = 0;
return node;
}
void enter_word(Tnode* root, string const &word) {
//if (root!=0) {
if (root->left==NULL||root->right==NULL) {
// First search for the node in the tree:
Tnode *node = root;
while (1) {
int order = word.compare(node->word);
if (order==0) { // Word is in the tree already
++node->count;
break;
} else {
Tnode *&next = order<0? node->left
: node->right;
if (next==0) { // Word not yet in tree?
next = new_Tnode(word);
break;
} else
node = next;
}
}
} else { // Create the first node at the root
root = new_Tnode(word);
}
}
void write(ostream &output, Tnode *node,
bool indent, int spaces = 2) {
if (node) {
write(output, node->left, indent, spaces+2);
if (indent)
for (int k = 0; k!=spaces; ++k)
cout << ' ';
output << node->word
<< " (" << node->count << ")\n";
write(output, node->right, indent, spaces+2);
}
}
int main() {
cout << "Enter words terminated by \"$done\"\n";
Tnode* tree;
while (1) {
string word;
cin >> word;
if (word=="$done") {
break;
}
enter_word(tree, word);
}
write(cout, tree, true /* do indent */);
return 0;
}
运行时错误,请帮忙解答一下
|
|