hash table

const int P = 13;
const int CAPCITY = 3;
const int DEFAULT_VAL = -1;
class myHash
{

public:
    typedef struct buck_node
    {
        int data[CAPCITY];
        struct buck_node* next;
    }buck_node;

    myHash()
    {
        buck_node* p = NULL;
        for (int i = 0; i < P; ++i)
        {
            for (int j = 0; j < sizeof(p->data) / sizeof(*(p->data)); ++j)
                hash_table[i].data[j] = DEFAULT_VAL;
            hash_table[i].next = NULL;
        }
    }

    int getHash(int x)
    {
        return x%P;
    }

    void show()
    {
        for (int i = 0; i < P; ++i)
        {
            buck_node* cur = &hash_table[i];
            cout <<endl<< "P=" << i << ":--> ";
            while (cur)
            {
                cout << "[";
                for (int i = 0; i < CAPCITY; ++i)
                {
                    cout << cur->data[i]<<" ";
                }
                cout << "]->";
                cur = cur->next;
            }
            cout <<"NULL"<< endl;
        }
    }

    void insert(int x)
    {
        int index = getHash(x);
        int pos = x%CAPCITY;

        buck_node* cur = &hash_table[index];

        while (cur->next && cur->data[pos] != DEFAULT_VAL)
            cur = cur->next;

        if (cur->data[pos]== DEFAULT_VAL)
            cur->data[pos] = x;
        else if (cur->next == NULL)
        {
            cur->next = BuyNode();
            cur = cur->next;
            cur->data[pos] = x;
        }



    }

    void find(int x)
    {
        int index = getHash(x);
        int pos = x%CAPCITY;

        buck_node* cur = &hash_table[index];
        int capcount = 1;
        while (cur && cur->data[pos] != x)
        {
            cur = cur->next;
            capcount++;
        }
        if (cur->data[pos] == x)
        {
            cout << "p:" << index << " capcount:" << capcount << " pos:" << pos;
            cout << " is:>" << x << endl;
        }
        else
        {
            cout << "not found" << endl;
        }


    }

    void Delete(int x)
    {

    }

protected:
    buck_node* BuyNode()
    {
        buck_node* p = new buck_node;
        for (int i = 0; i < CAPCITY; ++i)
            p->data[i] = DEFAULT_VAL;
        p->next = NULL;
        return p;
    }
private:
    buck_node hash_table[P];

};



void test()
{
    myHash IntHash;
    //IntHash.show();
    cout << "   " << endl;
    time_t a;
    srand((unsigned)time(&a));

    for (int i = 0; i < 3000; ++i)
        IntHash.insert(i);

    //IntHash.show();

    cout << "find(1494) " << endl;
    IntHash.find(1494);
}

void main()
{
    test();
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值