1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
|
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<iomanip>
using namespace std;
struct Display
{
string words;;
int count;
};
struct Node
{
Display value;
Node* pLeft;
Node* pRight;
};
Node* add(Node* tree, Display value);
Node* addNode(Node* tree, Node* toAdd);
bool treeContains(Node* tree, string word) ;
void displayAlphabetTree(Node* tree);
void removeLastPunctuation(string&);
int main()
{
string newword;
Display value;
bool eofReached = false;
value.count = 0;
Node* tree = 0;
ifstream myfile("speech.txt");
if(!myfile)
{
cout << "Error, can't open file" << endl;
exit(1);
}
else
{
while(!myfile.eof())
{
myfile >> newword;
removeLastPunctuation(newword);
newword = value.words;
eofReached = myfile.eof();
if (treeContains(tree, value.words) == false)
{
tree = add(tree, value);
}
}
}
displayAlphabetTree(tree);
myfile.close();
}
Node* add(Node* tree, Display value)
{
//tempPtr is a temporary pointer
Node* tempPtr = new Node;
tempPtr->value = value;
tempPtr->pLeft = 0;
tempPtr->pRight = 0;
return addNode(tree, tempPtr);
}
Node* addNode(Node* tree, Node* toAdd)
{
if (tree == 0)
{
return toAdd;
}
else
{
if(toAdd->value.words < tree->value.words)
{
tree->pLeft = addNode(tree->pLeft, toAdd);
return tree;
}
else if(toAdd->value.words == tree->value.words)
{
tree->value.count++;
return tree;
}
else
{
tree->pRight = addNode(tree->pRight, toAdd);
return tree;
}
}
}
bool treeContains(Node* tree, string word)
{
// If a word is in the binary
// tree then true is returned.
// Vice versia, false is returned if not.
if (tree == NULL)
{
// Tree is empty, so it certainly doesn't contain item.
return false;
}
else if (word == tree->value.words)
{
//The word matches to one in the root node.
return true;
}
else if (word < tree->value.words)
{
// The word is less than the one in the root node
// and must be sent to the left subtree.
return treeContains(tree->pLeft, word);
}
else
{
// The word is more than the one in the root node
// and must be sent to the right subtree.
return treeContains(tree->pRight, word);
}
}
void displayAlphabetTree(Node* tree)
{
if(tree != 0)
{
displayAlphabetTree(tree->pLeft);
displayAlphabetTree(tree->pRight);
cout<<tree->value.words<<" "<<"["<<tree->value.count<<"]"<<endl;
}
}
void removeLastPunctuation(string& newword)
{
if (newword.length() > 1) {
char chLast = char(newword[newword.length()-1]);
if (ispunct(chLast)) {
newword.erase(newword.length()-1, 1);
removeLastPunctuation(newword);
}
}
}
|