128 lines
3.4 KiB
C++
128 lines
3.4 KiB
C++
//下面给出哈希表的实现、插入以及打印代码:
|
||
#include<iostream>
|
||
#include <stdio.h>
|
||
#include <memory.h>
|
||
#include <string>
|
||
using namespace std;
|
||
|
||
#define DEFAULT_TABLE_LENGTH 7 // 哈希表默认表长
|
||
#define $ -1 // 默认初始化的值
|
||
#define ElemType nos_msg // 值类型
|
||
|
||
typedef struct nos_msg // 执行体消息
|
||
{
|
||
// 构造函数
|
||
nos_msg(int nodId,String msg)
|
||
{
|
||
this->nodId=nodId;
|
||
strcpy(this->msg, msg);
|
||
};
|
||
int nodId;
|
||
string msg;
|
||
}nos_msg;
|
||
|
||
typedef struct bucket_node // 节点类型
|
||
{
|
||
ElemType data[3];
|
||
struct bucket_node *next; // 每个节点能存放3个数据和一个指向另一个节点的指针
|
||
}bucket_node;
|
||
|
||
|
||
typedef bucket_node hash_table[P]; // 定义哈希表(实际就是一个数组)
|
||
|
||
/*初始化哈希表(数组)元素 */
|
||
void init_bucket_node(hash_table &ht, int i)
|
||
{
|
||
memset(&ht[i], $, sizeof(ElemType)*3);
|
||
memset
|
||
ht[i].next = 0;
|
||
}
|
||
|
||
/* 初始化哈希表 */
|
||
void init_hash_table(hash_table &ht)
|
||
{
|
||
for(int i = 0; i<DEFAULT_TABLE_LENGTH; ++i)
|
||
init_bucket_node(ht, i);
|
||
}
|
||
|
||
/* 哈希函数,得到元素x应当插入到哈希表的哪个下标 */
|
||
int hash(ElemType x)
|
||
{
|
||
return x % DEFAULT_TABLE_LENGTH;
|
||
}
|
||
|
||
/* 把元素x 插入到哈希表ht中 */
|
||
int insert_new_element(hash_table &ht, ElemType x)
|
||
{
|
||
int index = hash(x); //得到元素x应当插入到哈希表的哪个下标
|
||
for(bucket_node* p = &ht[index],*q = NULL; NULL!=p; q=p,p=p->next)
|
||
{ // 节点指针p 指向ht[index]节点
|
||
if(NULL != p->next) // 如果p->next == NULL,说明p所指节点的三个数据已经插满
|
||
continue; // 则p指向下一个节点
|
||
|
||
for(int i = 0; i<3; ++i)
|
||
{
|
||
if($ == p->data[i]) // 如果某个位置等于$,说明该位置为空,把x插入并返回
|
||
{
|
||
p->data[i] = x;
|
||
return 0;
|
||
}
|
||
}
|
||
}
|
||
if(NULL == p) // 如果 p == NULL,说明最后一个节点刚好插满,需要另外开辟一个节点的内存
|
||
{
|
||
bucket_node * s = new bucket_node;
|
||
memset(s, $, sizeof(ElemType)*3); // 初始化刚开辟的内存
|
||
s->next = NULL;
|
||
s->data[0] = x; // x 放入该节点的第一个位置
|
||
q->next = s; // 把s 挂到最后一个节点的下面
|
||
return 0;
|
||
}
|
||
return -1; // 如果没有在现有节点下找到位置,并且开辟节点也失败的话,x 就真的不能插入了
|
||
}
|
||
|
||
|
||
/* 打印哈希表 */
|
||
void show_hash_table(hash_table &ht)
|
||
{
|
||
bucket_node* p = NULL;
|
||
for(int i = 0; i<P; ++i) // 从第一个哈希表元素开始打印,知道最后一个元素
|
||
{
|
||
cout<<"ht["<<i<<"]"<<" : ";
|
||
for(p=&ht[i]; NULL!=p; p=p->next) // 打印下标为i的哈希表元素及该位置所链接的节点
|
||
{
|
||
for( int k = 0; 3>k && $!=p->data[k]; ++k) // p->data[k] != $ ,说明该位置不空,则打印
|
||
{
|
||
cout<<p->data[k]<<" ";
|
||
}
|
||
}
|
||
cout<<endl;
|
||
}
|
||
}
|
||
|
||
int main()
|
||
{
|
||
hash_table ht;
|
||
|
||
ElemType ar[] =
|
||
{
|
||
{1,"Success Message"},
|
||
{2,"OK Message"},
|
||
{3,"Error Message"},
|
||
{4,"Finish Message"},
|
||
{5,"Time Out Message"},
|
||
{6,"UNKNOW Message"}
|
||
}; // 测试数组
|
||
|
||
init_hash_table(ht); // 初始化哈希表
|
||
|
||
for(int i = 0; i<sizeof(ar)/sizeof(*ar); ++i)
|
||
insert_new_element(ht, ar[i]); // 数组元素依次插入哈希表
|
||
|
||
show_hash_table(ht); // 打印哈希表
|
||
|
||
cout<<"Over"<<endl;
|
||
|
||
return 0;
|
||
|
||
} |