Hash表
#ifndef _HASH_H #define _HASH_H #include<string.h> #include<stdio.h> class HashTable { public: HashTable(unsigned int size); ~HashTable(); int get(const char *key,unsigned int *value); int set(const char *key,unsigned int value); int push(const char *key); int MAXTopK(unsigned int k); int MINTopK(unsigned int k); private: struct Node { char *key; unsigned int value; Node *next; Node(const char *str,unsigned int v) { key = new char[strlen(str)+1]; strcpy(key,str); value = v; next = NULL; } ~Node() { delete[] key; } }; int Init(); int Destroy(); int Hash(const char *key,unsigned int *hashcode); int ClearChain(Node *Head); Node **TableHead; unsigned int TableSize; char **kWords; }; #endif
#include"Hash.h" #include"Heap.h" HashTable::HashTable(unsigned int size) { TableHead = NULL; TableSize = size; Init(); } HashTable::~HashTable() { Destroy(); } int HashTable::Init() { if(TableHead != NULL) { printf("HashTable has been initialized "); return -1; } TableHead = new Node*[TableSize]; for(unsigned int i=0;i<TableSize;i++) { TableHead[i]=NULL; } return 0; } int HashTable::Destroy() { for(unsigned int i=0;i<TableSize;i++) { if(ClearChain(TableHead[i]) < 0) { printf("ClearChain error "); return -1; } } delete[] TableHead; TableHead = NULL; return 0; } int HashTable::get(const char *key,unsigned int *value) { unsigned int hashcode=0; if(Hash(key,&hashcode) < 0) { printf("generate hashcode error"); return -1; } unsigned int index = hashcode%TableSize; Node *p = TableHead[index]; while(p!=NULL && (strcmp(key,p->key)!=0)) { p=p->next; } if(p!=NULL) { *value = p->value; } else { *value = 0; } return 0; } int HashTable::set(const char *key,unsigned int value) { unsigned int hashcode=0; if(Hash(key,&hashcode) < 0) { printf("generate hashcode error"); return -1; } unsigned int index = hashcode%TableSize; Node *p = TableHead[index]; while(p!=NULL && (strcmp(key,p->key)!=0)) { p=p->next; } if(p!=NULL) { p->value = value; } else { Node *q = TableHead[index]; TableHead[index] = new Node(key,value); TableHead[index]->next = q; } return 0; } int HashTable::push(const char *key) { unsigned int hashcode=0; if(Hash(key,&hashcode) < 0) { printf("generate hashcode error"); return -1; } unsigned int index = hashcode%TableSize; Node *p = TableHead[index]; while(p!=NULL && (strcmp(key,p->key)!=0)) { p=p->next; } if(p!=NULL) { p->value = p->value+1; } else { Node *q = TableHead[index]; TableHead[index] = new Node(key,1); TableHead[index]->next = q; } return 0; } int HashTable::Hash(const char *str,unsigned int *hashcode) { *hashcode = 0; unsigned int hashseed = 131; while(*str != '