数据结构 查找 散列表(Hash)(1)

来源:互联网 发布:无印良品文具淘宝 编辑:程序博客网 时间:2024/05/28 05:13

1.代码如下

#include <bits/stdc++.h>#define MAXSIZE 0x64using namespace std;typedef struct node{    int key;    int index;//管控下标    struct node* next;} *Hnode;typedef struct hnode{    Hnode data[MAXSIZE];    int length;} HasTable;void createHas(HasTable &ht);void printHsh(HasTable ht);int searchHas(HasTable ht, int key);int main() {    HasTable ht;    cout << "请输入散列表的长度:\n";    cin >> ht.length;    cout << "- - - - - - - - -1.散列表构造- - - - - - - - -\n";    createHas(ht);    cout << "散列表构造完成...\n";    cout << "\n- - - - - - - - -2.打印散列表- - - - - - - - -\n";    printHsh(ht);    cout << "\n- - - - - - - - -3.散列表查找- - - - - - - - -\n";    int key;    cout << "请输入你要查找的数:\n";    cin >> key;    int index = searchHas(ht, key);    if(index == -1) {        cout << "查找失败!\n" << "序列中不存在此数..." << endl;    }    return 0;}void createHas(HasTable &ht) {    cout << "链表数组头节点初始化...\n";    for(int i = 0; i <= ht.length; i++) {        ht.data[i] = new node;        ht.data[i]->next = NULL;    }    HasTable h0 = ht;    h0.length = ht.length;    cout << "请输入长度为" << h0.length << "的序列元素:\n";    for(int i = 0; i < h0.length; i++) {        int key;        cin >> key;        int index = key % (h0.length + 1);        for(int j = 0; j <= h0.length; j++) {            if(index == j) {                Hnode p = new node;                p->key = key;                h0.data[j]->key = p->key;                h0.data[j]->index = i;                p->next = h0.data[j]->next;                h0.data[j]->next = p;                h0.data[j] = p;                j = (h0.length + 1);            }        }    }}void printHsh(HasTable ht) {    for(int i = 0; i <= ht.length; i++) {        Hnode h0 = ht.data[i];        cout << "#";        while(h0->next) {            cout << "->" << h0->key;            h0 = h0->next;        }        cout << endl;    }}int searchHas(HasTable ht, int key) {    int index = key % (ht.length + 1);    for(int i = 0; i <= ht.length; i++) {        if(index == i) {            if(ht.data[i]->next == NULL) {                return -1;            }            Hnode h0 = ht.data[i];            while(h0->next) {                if(key == h0->key) {                    cout << "查找成功!\n" << "该关键字在第" << index << "块,处于原序列的下标为:" << h0->index << ",地址为:" << h0 << endl;                    return h0->index;                }                h0 = h0->next;            }            return -1;        }    }}

2.效果如下


原创粉丝点击