C++哈希表

#include <iostream>
#include <string.h>
#define MAX 13
using namespace std;

template<typename Type>
struct Node
{
    Type *data;
    Node *next;
    Node(const Type *str = "") :data(new Type[strlen(str) + 1]), next(NULL)
    {
        strcpy(data,str);
    }
};
template<typename Type>
struct Mnode
{
    Node<Type> *adj;
    int count;//计数。
    Mnode() :adj(NULL), count(0){}
};

template<typename Type>
class Hash
{
public:
    Hash(){}
    long hash(const char *str)
    {
        const char *p = str;
        long nhash=0;
        while (*p)
            nhash = (nhash << 5) + nhash + *p++;
        return nhash;
        //Times33算法。
    }
    void Insert(const char *str)
    {
        Node<Type> *s = new Node<Type>(str);
        long key = hash(str)%MAX;
        Node<Type> *p = node[key].adj;
        Node<Type> *pr = NULL;
        while (p != NULL)
        {
            pr = p;
            p = p->next;
        }
        if (pr == NULL)
        {
            node[key].adj = s;
        }
        else
        {
            s->next = p;
            pr->next = s;
        }
        node[key].count++;
    }
    void Printf()
    {
        int i = 0;
        Node<Type> *p = NULL;
        for (; i < MAX; i++)
        {
            if (node[i].count>0)
            {
                p = node[i].adj;
                while (p != NULL)
                {
                    cout << p->data << "  ";
                    p = p->next;
                }
                cout << endl;
            }
        }
    }
private:
    Mnode<Type> node[MAX];
};


int main()
{
    Hash<char> sh;
    sh.Insert("liuuiyan");
    sh.Insert("benleng");
    sh.Insert("huang");
    sh.Printf();
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值