自己手撸了一下拉链法解决散列冲突的算法,代码如下:


#include <iostream>
#include <vector>
#define N 1000
using namespace std;
typedef struct ChainNodes {
    int data;
    ChainNodes* Next;
}ChainNodes;
void CreatHashTable(vector<ChainNodes*>& try01) {
    //ChainNodes** try01 = new ChainNodes * [10];//try应该是关键字
    for (int i = 0; i < try01.size(); i++) {
        try01[i] = NULL;
    }
    cout << "请输入您要储存的数字" << endl;
    int item, i = 0;
    char t;
    while (cin >> item) {
        //“=”在C语言中优先级中最低;
        i = item % 7;
        if (try01[i] == NULL) {
            try01[i] = new ChainNodes;
            try01[i]->data = item;
            try01[i]->Next = NULL;
        }
        else {
            ChainNodes* pre = try01[i];
            ChainNodes* cur = try01[i]->Next;
            while (cur != NULL) {
                pre = cur;//“=”在C语言中优先级中最低;
                cur = cur->Next;
            }
            pre->Next = new ChainNodes;/*这段代码的目的是进行链表的尾插法;但是当try指向空节点时,没有一个临时指针保存try01的前继节点,导致try01
                                      指向一片和链表中断的空间,之后再把temp赋给try01,则原先try01【i】所指的空间失去连接,导致内存泄漏*/
            pre->Next->data = item;
            pre->Next->Next = NULL;
            
        };
        if ((t = cin.get()) == '\n')      break;
    }

};

void QueryNum(vector<ChainNodes*>& try01) {
    cout << "请输入您要查询的数" << endl;
    int tem;
    cin >> tem;
    if (try01[tem % 7] == NULL) {
        cout << "您要查询的数不存在" << endl;
    }
    else {
        ChainNodes* temp = try01[tem % 7];
        int count = 0;
        while (temp != NULL) {
            count++;//
            if (temp->data == tem) {
                cout << "您找的数位于散列表第" << tem % 7 << "个表的第" << count << "个链表中" << endl;
                break;
            }
            temp = temp->Next;
        }
        if (temp == NULL) {
            cout << "您要查询的数不存在" << endl;

        }
    }
}

void DeleteHashTable(vector<ChainNodes*>& try01) {
    for (int i = 0; i < try01.size(); i++) {
        if (try01[i] == NULL) {
            cout << "第"<<i<<"位链表为空,无需释放。" << endl;
        }
        else {
            ChainNodes* temp = try01[i];
            int count = 0;
            while (temp != NULL) {
                ChainNodes* t = temp;
                cout << t->data << endl;
                temp = temp->Next;
                delete t;
            }
            if (temp == NULL) {
                try01[i] = NULL;
                cout << "第"<<i<<"位链表已经释放完毕" << endl;

            }
        }

    }

}

int main()
{
    vector<ChainNodes*> try01(10);
    CreatHashTable(try01);
   QueryNum(try01);
   DeleteHashTable(try01);
    return 0;
}

 欢迎大家交流讨论;

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐