哈希表之笔试题

现在有一个用来存放整数的Hash表,Hash表的存储单位称为桶,每个桶能放3个整数,当一个桶中要放的元素超过3个时,则要将新的元素存放在溢出桶中,每个溢出桶也能放3个元素,多个溢出桶使用链表串起来。此Hash表的基桶数目为素数PHash表的hash函数对P取模。

   题目的大致意思就是上述的,下面给出个人的代码:

<pre name="code" class="plain">#include<iostream>
#include<stdlib.h>
#include<assert.h>

using namespace std;

#define P 7
#define BUCKET_NODE_SIZE 3
#define NULL_DATA -1

struct bucket_node
{
    int data[BUCKET_NODE_SIZE];
    struct bucket_node *next;
};

bucket_node hash[P];

void Init_Hash_Table(bucket_node (&hash)[P])
{
    int i = 0;
    for(i = 0;i < P; ++i){
        for(int j = 0;j < BUCKET_NODE_SIZE;++j){
            hash[i].data[j] = NULL_DATA;
        }
        hash[i].next = NULL;
    }
}

void Insert_New_Element(int &t)
{
    int index = t % P;
    int i = 0;
    for(i = 0;i < BUCKET_NODE_SIZE;++i){
        if(hash[index].data[i] == NULL_DATA){
            hash[index].data[i] = t;
            return;
        }
    }
    bucket_node *p = &hash[index];
    while(p->next != NULL){
        p = p->next;
        for(int i = 0;i < BUCKET_NODE_SIZE; ++i){
            if(p->data[i] == NULL_DATA){
                p->data[i] = t;
                return;
            }
        }
    }
    bucket_node *s = (bucket_node*)malloc(sizeof(bucket_node));
    assert(s != NULL);
    for(int i = 0; i < BUCKET_NODE_SIZE; ++i){
        s->data[i] = NULL_DATA;
    }
    s->next = NULL;
    s->data[0] = t;
    p->next = s;
}

void Show_Hash()
{
    int i = 0;
    for(i = 0; i < P; ++i){
        cout << "i = "<< i << " : ";
        for(int j = 0; j < BUCKET_NODE_SIZE; ++j){
            if(hash[i].data[j] != NULL_DATA){
                cout << hash[i].data[j] << " ";
            }
        }
        bucket_node *p = &hash[i];
        while(p->next){
            p = p->next;
            for(int k = 0; k < BUCKET_NODE_SIZE; ++k){
                if(p->data[k] != NULL_DATA){
                    cout << p->data[k] << " ";
                }
            }
        }
        cout << endl;
    }
    cout << endl;
}


 
 
测试程序如下:

int main(int argc,char**argv)
{
    int array[] = {15,14,21,87,96,293,35,24,149,19,63,16,103,77,5,153,145,356,51,68,705,453 };
    int n = sizeof(array) / sizeof(int);
    Init_Hash_Table(hash);
    for(int i = 0; i < n; ++i){
        Insert_New_Element(array[i]);
    }
    Show_Hash();
    return 0;
}

其执行结果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值