我是一个学习数据结构的学生,试图实现一个hashmap函数,该函数将使用链表的节点添加元素。当我调用next value时,我在else语句中得到了一个段错误,并且我不知道为什么。感谢您的帮助,谢谢大家。
void insertMap (struct hashMap * ht, KeyType k, ValueType v)
{ /*write this*/
int idx = stringHash1(k);
struct hashLink * hlnk;
struct hashLink * plink;
assert(ht);
if(ht->table[idx] == NULL){
hlnk = (struct hashLink *) malloc(sizeof(struct hashLink));
hlnk->value = v;
hlnk->key = k;
hlnk->next = NULL;
ht->table[idx] = hlnk;
ht->count++;
}
else{
plink = ht->table[idx];
hlnk = (struct hashLink *) malloc(sizeof(struct hashLink));
hlnk->value = v;
hlnk->key = k;
hlnk->next = plink->next;
plink->next = hlnk;
ht->count++;
}
}发布于 2019-05-10 12:07:17
如果您尝试在列表的前面插入节点,则还需要更新ht->table[idx]。
当前您正在更新else案例中的本地指针plink。
else{
.....
plink->next = hlnk; //this line only updates the local pointer
ht->count++;
}它应该是
else{
.....
ht->table[idx] = hlnk;
}https://stackoverflow.com/questions/56070485
复制相似问题