栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ hash实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ hash实现

#include 
#include 
#include 
using namespace std;
#define max_size 1000

typedef struct node* List;
struct node{
    int val;
    List next;
};

typedef struct h_node* HashTabel;
struct h_node{
    int size;
    List head;
};
int next_prime(int n) {
    int p = n%2 ? n+2 : n+1;
    int i;
    while(n < max_size) {
        for(i=(int)sqrt(p); i>2; i--) {
            if(p%i==0)
                break;
        }
        if(i==2)
            return p;
        else    
            p += 2;
    }
    return p;

}

HashTabel init_hash(int size) {
    int new_size = next_prime(size);
    HashTabel H = new h_node;
    H->size = new_size;
    H->head = new node[new_size];
    for(int i=0; ihead[i].next = NULL;

    return H;
}

int Hash(HashTabel H, int key) {
    return key % H->size;
}

List Find(HashTabel H, int key) {
    int pos = Hash(H, key);
    List p = H->head[pos].next;
    while(p && p->val!=key)
        p = p->next;
    return p;
}

bool insert(HashTabel H, int key) {
    List tmp = Find(H, key);
    if(!tmp) {
        int pos = Hash(H, key);
        tmp = H->head[pos].next;        // 不定义新变量了,直接用

        List new_node = new node;
        new_node->val = key;
        new_node->next = tmp;
        H->head[pos].next = new_node;
        return true;

    }
    else
        return false;

}

void show(HashTabel H ) {
    int n = H->size;
    for(int i=0; i
        cout << i << " : ";
        List p = H->head[i].next;
        while(p) {
            cout << p->val << ' ';
            p = p->next;
        }
        cout << endl;
    }
}

int main()
{
    HashTabel H = init_hash(10);
    int arr[] = {47,7,29,11,16,92,22,8,3,50,37,89,94,21};      // n=14
    for(int i=0; i<14; i++) 
        insert(H, arr[i]);
    show(H);


    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853327.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号