Trie数据结构的实现
Implementation of Trie data structure
我是编程新手。我正在尝试实现Trie数据结构。但是每当我试图在trie中插入一个字符串时,就会出现分段错误。
这是节点类
class Node{
public:
Node *key[2];
Node *parent;
bool EOW;
Node1(){
this->key[0]=NULL;
this->key[1]=NULL;
this->parent = NULL;
this->EOW = false;
}
};
这是trie类
class Trie{
public:
Node *root;
Trie(){
root = new Node();
}
void insertUtil(Node *root, char a[]);
void insert(char a[]){
// cout << root <<endl;
// cout << root->key[0];
insertUtil(root, a);
}
};
这就是insertUtil函数
void Trie::insertUtil(Node *root, char a[]){
Node *temp = root;
for(int idx=0;idx<5;idx++){
cout << idx <<endl;
int tmp_chr = a[idx]-'0';
if(!(temp->key[1])){
temp->key[a[idx]-'0'] = new Node();
temp->key[a[idx]-'0']->parent = temp;
}
temp = temp->key[a[idx]-'0'];
}
temp->EOW = -1;
}
int main(){
Trie t1;
char b[5];
cin >> b;
t1.insert(b);
cout << '*';
cin >> b;
t1.insert(b);
cin >> b;
t1.insert(b);
cin >> b;
t1.insert(b);
}
Node
的成员key
声明为
Node *key[2];
所以它是一个由两个指针组成的数组,给定Trie::insertUtil
中的这一行,
int tmp_chr = a[idx]-'0'; // A variable ignored in the following code, BTW.
我假设OP试图插入的"字符串"仅由字符'0'
和'1'
组成。
请注意,在发布的代码中,所使用的C字符串中所需的null终止符被简单地忽略,这本身就是一个错误,通过使用适当的std::string
很容易修复。
另一个问题也在同一个循环中:
for(int idx = 0; idx < 5; idx++)
{ // ^^^^^^^ It should stop before the null-terminator
// (...)
int tmp_chr = a[idx]-'0'; // Are you sure that there are only '0' or '1'?
if( !(temp->key[1]) )
{ // ^^^ 1 is wrong, here, it should be temp->key[tmp_chr]
temp->key[a[idx]-'0'] = new Node();
// ^^^^^^^^^^ Why not use tmp_chr here and in the following?
// ...
}
// ...
}
相关文章:
- 如何使用set实现无序数据结构?
- 如何知道用于实现标准代码段的确切数据结构和算法,例如在C++STL中?
- 如何在C++中实现节点数任意的通用树数据结构?
- C++ 中的 TRIE 数据结构实现
- Trie数据结构的实现
- 实现具有浮点键的类似哈希表的数据结构,其中公差内的值被合并在一起
- 数据结构实现
- 与shared_ptr相比,更小的运行时数据结构和更快的代码可实现独特的_ptr
- C++:如果 std::atomic_flag 是唯一的无锁原子类型,如何在C++中实现无锁数据结构?
- unordered_set是否适合存储矢量<int>元素的数据结构?如果是这样,我将如何实现哈希函数?
- 我应该使用什么样的数据结构来实现UPGMA
- 我应该如何在恒定长度的 STL 样式数据结构中实现max_size?
- 如何使用 C++ 实现堆数据结构
- 堆栈(数据结构)实现
- 如何实现数据结构,就像C 中的数组一样支持不同的类型元素
- 我需要一个像堆栈一样的数据结构,但具有随机访问,但是,我应该实现什么
- 在Haskell中使用O(1)元素访问实现高效的类似拉链的数据结构
- STL如何用非线性数据结构实现反向迭代器去引用
- 实现数据结构时的智能指针或原始指针
- 将值映射到像素对-如何实现数据结构