http://blog.csdn.net/flying0033/article/details/7063608
散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
下面的哈希表函数使用了(除留余数)
头文件:HashTable.h
- #ifndef HASHTABLE_H
- #define HASHTABLE_H
- #define MAXSIZE 17
- #define NULLKEY -32768
- typedef struct node{ //关键字结点
- int data; //关键字
- struct node *next; //指向下一个结点
- }Node;
- typedef struct Table{
- Node *table; //动态分配哈希表
- int count; //哈希表的关键字个数
- }HashTable;
- void InitHashTable(HashTable *H); //初始化哈希表
- int Hash(int key); //哈希表函数
- void InsertHashTable(HashTable *H,int key); //把关键字插入哈希表
- bool SearchHashTable(HashTable *H,int key); //在哈希表中查找关键字key
- #endif //HASHTABLE_H
实现文件:HashTable.cpp
- #include "HashTable.h"
- #include <stdio.h>
- #include <stdlib.h>
- void InitHashTable(HashTable *H) //初始化哈希表
- {
- H->count = MAXSIZE; //初始化哈希表的大小
- H->table = (Node *)malloc(sizeof(Node) * H->count); //创建哈希表
- for(int i = 0;i < H->count;++i) //初始化哈希表的数据
- {
- H->table[i].data = NULLKEY;
- H->table[i].next = NULL;
- }
- }
- int Hash(int key) //哈希表函数
- {
- return key % MAXSIZE;
- }
- void InsertHashTable(HashTable *H,int key) //将关键字key插入哈希表
- {
- int addr = Hash(key);
- if(H->table[addr].data != key && H->table[addr].data != NULLKEY) //如果为真,创建单链表
- {
- Node *temp = (Node *)malloc(sizeof(Node));
- temp->next = H->table[addr].next;
- temp->data = key;
- H->table[addr].next = temp;
- }
- else if(H->table[addr].data == NULLKEY) //则否直接填入
- H->table[addr].data = key;
- }
- bool SearchHashTable(HashTable *H,int key) //查找关键字key的值
- {
- int addr = Hash(key);
- if(H->table[addr].data == key)
- return true;
- Node *p = H->table[addr].next;
- while(p != NULL) //查找单链表
- {
- if(p->data == key)
- return true;
- else
- p = p->next;
- }
- return false;
- }
测试文件:main.cpp
- #include "HashTable.h"
- #include <stdio.h>
- int main()
- {
- HashTable H;
- InitHashTable(&H);
- for(int i = 0;i < MAXSIZE * 2;i += 2)
- InsertHashTable(&H,i);
- printf("请输入要查找的内容:\n");
- int key;
- scanf("%d",&key);
- if(SearchHashTable(&H,key))
- printf("在哈希表中找到关键字:%d\n",key);
- else
- printf("在哈希表中未找到关键字:%d\n",key);
- return 0;
- }