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
| #include<iostream> using namespace std; const int MaxChSize = 26; const int LinkSize = 27;
typedef enum { ELEM = 1, BRCH = 2 } NodeType;
typedef struct { char ch[MaxChSize]; int CurSize; }KeyType;
typedef struct { KeyType key; void* InfoPtr; }ElemType;
struct TrieNode;
typedef struct { TrieNode* Link[LinkSize]; }BranchNode;
typedef struct TrieNode { NodeType Ttype; union { ElemType elem; BranchNode brchNode; }; }TrieNode;
class TrieTree { private: TrieNode* root; public: TrieTree() : root(nullptr) {} ~TrieTree() {} private: int TransIndex(const KeyType& kch, int k) { int index = 0; if (k < kch.CurSize) { index = kch.ch[k] - 'a' + 1; } return index; } TrieNode* BuyTrieNode() { TrieNode* p = (TrieNode*)malloc(sizeof(TrieNode)); if (nullptr == p) exit(-1); memset(p, 0, sizeof(TrieNode)); return p; } TrieNode* MakeElemNode(const ElemType& item) { TrieNode* s = BuyTrieNode(); s->Ttype = ELEM; s->elem = item; return s; } TrieNode* MakeBrchNode(TrieNode* ptr, int k) { TrieNode* s = BuyTrieNode(); s->Ttype = BRCH; int index = TransIndex(ptr->elem.key, k); s->brchNode.Link[index] = ptr; return s; } void Insert_item(TrieNode*& ptr, const ElemType& item, int k) { if (nullptr == ptr) { ptr = MakeElemNode(item); } else if (ptr->Ttype == BRCH) { int index = TransIndex(item.key, k); Insert_item(ptr->brchNode.Link[index], item, k + 1); } else if (ptr->Ttype == ELEM) { ptr = MakeBrchNode(ptr, k);
int index = TransIndex(item.key, k);
Insert_item(ptr->brchNode.Link[index], item, k + 1); } } public: TrieNode* FindTrieNode(const KeyType& key) { TrieNode* p = root; int k = 0; while (p != nullptr && p->Ttype == BRCH) { int index = TransIndex(key, k); p = p->brchNode.Link[index]; ++k; } if (p != nullptr && strcmp(p->elem.key.ch, key.ch) != 0) { p = nullptr; } return p; }
bool Insert(const ElemType& item) { TrieNode* res = FindTrieNode(item.key); if (nullptr != res) return false;
int k = 0; Insert_item(root, item, k); return true; } };
|