数据结构与算法之散列表(拉链法解决散列冲突)

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


#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;
}

 欢迎大家交流讨论;

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值