【数据结构】C++ hash实现

#include <iostream>
#include <string>
#include <cmath>
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; i<new_size; i++)
        H->head[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<n; 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值