#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;
}
C++哈希表
最新推荐文章于 2024-07-13 19:30:43 发布