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

遍历哈希表链表实现基数排序时触发段错误问题求助

问题分析与修复

你的代码存在两个关键问题,共同导致了段错误:

1. 空链表时的非法指针访问

在insert函数中,当对应哈希桶的链表为空(H[index] == nullptr)时,q被赋值为nullptr,此时直接访问q->next会触发段错误。你之前添加的if(q)仅处理了链表非空的情况,完全遗漏了链表为空时的逻辑。

正确逻辑应为:

  • 若链表为空,直接将新节点设为链表头(H[index] = p)
  • 若链表非空,再遍历到尾部插入新节点

2. 数组遍历的边界错误

main函数里的for循环条件i < sizeof(a)是错误的:sizeof(a)返回数组总字节数(对于9个int元素的数组,通常是36字节),这会让循环执行36次,远远超出数组实际的9个元素,触发数组越界访问,同样会导致未定义行为(包括段错误)。

正确的循环条件应该是i < sizeof(a)/sizeof(a[0]),以此计算数组的实际元素个数。


修复后的完整代码

#include <iostream>
using namespace std;

class HASH {
    private:
        struct node {
            int info;
            node *next;
        };

        node *H[10];

    public:

        void initHashTable() {
            for (int i = 0; i < 10; i++) {
                H[i] = nullptr;
            }
        }

        void insert(int x) {
            int index = hashUnit(x);

            node *p = new node;
            p->info = x;
            p->next = nullptr;

            node *q = H[index];
            if (q == nullptr) {
                // 链表为空,直接作为头节点
                H[index] = p;
            } else {
                // 遍历到链表尾部
                while (q->next != nullptr) {
                    q = q->next;
                }
                q->next = p;
            }
        }

        int hashUnit(int x) {
            int index = x % 100 % 10;
            return index;
        }

        void display() {
            for (int i = 0; i < 10; i++) {
                cout << "H1[" << i << "]---&gt;";

                node *p = H[i];
                while (p != NULL) {
                    cout << p->info << "---&gt;";
                    p = p->next;
                }

                cout << "NULL" << endl;
            }
        }

};

int main() {
    int a[9] = {199, 200, 77, 45, 15, 278, 66, 9, 100};

    HASH h;
    h.initHashTable();

    // 计算数组元素个数,避免越界
    int arrSize = sizeof(a)/sizeof(a[0]);
    for (int i = 0; i < arrSize; i++) {
        h.insert(a[i]);
    }

    h.display();
}

修复说明

  1. insert函数空链表处理:新增if (q == nullptr)判断,链表为空时直接将新节点赋值给哈希桶头指针,彻底避免空指针访问。
  2. 数组遍历边界修正:通过sizeof(a)/sizeof(a[0])计算实际元素个数,确保循环只遍历数组内存在的元素,杜绝越界问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:25:30