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

从全局哈希表读取数据到链表时出现运行时错误,请求排查

问题分析与修复方案

核心问题

  • 链表拼接逻辑完全错误:else分支里的c = locallinkedlist; locallinkedlist = c;没有实现节点添加,反而会破坏原哈希表的链表结构,导致遍历出现死循环或野指针,触发运行时错误。
  • 链表不支持二分查找:二分查找需要随机访问元素,链表只能顺序遍历,后续若要做二分查找,需将数据转存到数组中。

修复后的代码

先修正链表拼接逻辑,同时避免破坏原哈希表结构(通过创建新节点拷贝数据):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 假设node结构体定义如下(根据实际情况调整)
typedef struct node {
    char employeefirstname[50];
    // 其他员工字段...
    struct node *next;
} node;

extern node *hashtable[25]; // 全局哈希表

int main() {
    node *locallinkedlist = NULL;
    node *tail = NULL; // 尾指针,高效定位链表末尾

    // 从哈希表读取数据到本地链表
    for(int p = 0; p < 25; p++)
    {
        for(node *c = hashtable[p]; c != NULL; c = c->next)
        {
            // 分配新节点内存
            node *new_node = malloc(sizeof(node));
            if(new_node == NULL) {
                perror("malloc failed");
                exit(EXIT_FAILURE);
            }
            // 拷贝原节点数据到新节点
            strncpy(new_node->employeefirstname, c->employeefirstname, sizeof(new_node->employeefirstname)-1);
            new_node->employeefirstname[sizeof(new_node->employeefirstname)-1] = '\0'; // 确保字符串结束
            // 拷贝其他字段...
            new_node->next = NULL;

            // 添加到本地链表
            if(locallinkedlist == NULL)
            {
                locallinkedlist = new_node;
                tail = new_node;
            }
            else
            {
                tail->next = new_node;
                tail = new_node;
            }
        }
    }

    // 打印验证
    for(node *h = locallinkedlist; h != NULL; h=h->next)
    {
        printf("%s ", h->employeefirstname);
    }
    printf("\n");

    // 释放链表内存,避免泄漏
    node *temp;
    while(locallinkedlist != NULL) {
        temp = locallinkedlist;
        locallinkedlist = locallinkedlist->next;
        free(temp);
    }

    return 0;
}

补充说明

  • 如果直接复用原哈希表节点,会破坏原哈希表的链表结构,因此建议创建新节点拷贝数据。
  • 若要实现二分查找,需将链表数据转存到数组,排序后再执行二分查找操作。

内容的提问来源于stack exchange,提问作者Matthew Manning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:30:52