You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改C语言二次探测哈希查找函数以修改数组匹配元素的值

解决方案

你只需要针对匹配成功的逻辑做两处调整即可:

  1. 原代码中key == 99999999是相等判断语句,既不会修改变量值,也操作不到数组h,要替换为针对数组下标的赋值语句
  2. 可按需选择是否在匹配后跳出循环,避免无效遍历

调整后的完整代码

void search()
{
    int key, index, i, flag = 0, hkey;
    // 可按需修改为你想要设置的目标值,示例用99999999
    int new_val = 99999999;

    printf("\nenter search element\n");
    scanf("%d", &key);
    hkey = key % TABLE_SIZE;
    for(i = 0; i < TABLE_SIZE; i++)
    {
        index = (hkey + i * i) % TABLE_SIZE;
        if(h[index] == key)
        {
            printf("\n value is found at index %d \t original value =  %d", index, key);
            // 核心修改:给数组对应下标赋值
            h[index] = new_val;
            printf("\n value after modification: %d", h[index]);
            flag = 1;
            // 如果只需要修改第一个匹配到的元素,保留break;要修改所有匹配项就删除这行
            break;
        }
    }
    if(flag == 0) {
        printf("\n the searched element %d is not found", key);
    }
}

补充说明:这段代码用的是二次探测哈希的查找逻辑,正常哈希表中同一个key只会存一次,所以加break跳出循环是更合理的选择。

内容的提问来源于stack exchange,提问作者Can Balaman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:36:02