/* Name: Hash Copyright: Author: huowolf Date: 27/06/15 20:57 Description: HashTable的简单实现 */ #include <iostream> using namespace std; #define MAXSIZE 17 //该值最好采用某个4n+3形式的素数 #define NULLKEY -1 #define Exist 0 typedef struct node { int data; struct node *next; }Node; //关键字节点 typedef struct Table{ Node * table; int size; }HashTable; /* 本程序采用除留余数法构造哈希函数, 采用链地址法解决冲突 */ void InitHashTable(HashTable *H); void InsertHashTable(HashTable *H,int key); bool SearchHashTable(HashTable *H,int key); bool DeleteHashTable(HashTable *H,int key); void Display(HashTable *H); int main() { HashTable H; InitHashTable(&H); cout<<"请输入你要插入的一组数据,以-1结束输入:"; int i,key; while(1) { cin>>i; if(i==-1) break; InsertHashTable(&H,i); } Display(&H); cout<<"请输入你要查找的内容:"; cin>>key; if(SearchHashTable(&H,key)) cout<<"在哈希表中找到该关键字"<<key<<endl; else cout<<"哈希表中不存在着关键字"<<key<<endl; cout<<"请输入你要删除的内容:"; cin>>key; bool result = DeleteHashTable(&H,key); if(result) cout<<"关键字"<<key<<"已经成功删除"<<endl; else cout<< "关键字"<<key<<"不存在"<<endl; Display(&H); return 0; } void InitHashTable(HashTable *H) { H->size = MAXSIZE; H->table = new Node[H->size]; //初始化哈希表的数据,方便对该位置是否存在冲突进行判别 for (int i = 0; i < H->size; ++i) { H->table[i].data = NULLKEY; H->table[i].next = NULL; } } int Hash(int key) //hash函数 { return key%MAXSIZE; } void InsertHashTable(HashTable *H,int key) //插入数据到hash表 { int addr = Hash(key); if(H->table[addr].data==NULLKEY) { H->table[addr].data = Exist; Node *p = new Node; p->data = key; p->next = H->table[addr].next; H->table[addr].next = p; } else { Node *p = new Node; p->data = key; p->next = H->table[addr].next; H->table[addr].next = p; } } bool SearchHashTable(HashTable *H,int key) //查找关键字key的值 { int addr = Hash(key); Node *p = H->table[addr].next; while(p!=NULL) { if(p->data==key) return true; else p = p->next; } return false; } bool DeleteHashTable(HashTable *H,int key) //删除关键字 { int addr = Hash(key); Node *pCur = &H->table[addr]; //当前节点 Node *pPre = pCur; //前一个节点 while(pCur->next) { if(pCur->data==key) { pPre->next = pCur->next; delete pCur; pCur = NULL; return true; } else { pPre = pCur; pCur = pCur->next; } } return false; } void Display(HashTable *H) { cout<<"该哈希表中存在如下元素:"<<endl; Node *p; for(int i=0;i<MAXSIZE;i++) { if(H->table[i].data!=NULLKEY) { p = H->table[i].next; while(p) { cout<<p->data<<" "; p = p->next; } cout<<endl; } } }
原文地址:http://blog.csdn.net/huolang_vip/article/details/46671161