[Data structure] C++ hash implementation

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

Guess you like

Origin blog.csdn.net/ayitime/article/details/124554315