hash table

http://blog.chinaunix.net/uid-26779539-id-3238274.html


 5 struct HashNode
  6 {
  7   char* key;
  8   int count;
  9 };
 10 const int hashSize = 15;
 11 class HashTable
 12 {
 13   private:
 14     HashNode hashTable[hashSize];
 15   public:
 16     HashTable() {
 17       for (int i = 0; i < hashSize; ++i) {
 18         hashTable[i].count = 0;
 19         hashTable[i].key = NULL;
 20       }
 21     }
 22     ~HashTable() {
 23       for (int i = 0; i < hashSize; ++i)
 24         if (hashTable[i].key)
 25           delete hashTable[i].key;
 26     }
 27     int hashIndex (int key, char* value) {
 28       int index = key % hashSize;
 29       if (hashTable[index].count != 0)
 30         if (strcmp(hashTable[index].key, value) == 0)
 31           return index;
 32         else
 33           return hashIndex((key + 1), value);
 34       return index;
 35     }
 36     int hashValue(char * value) {
 37       int key = 0;
 38       for (int i = 0; value[i] != 0; i++) {
 39         key = key + (int)value[i];
 40       }
 41       cout<<key<<endl;
 42       return hashIndex(key, value);
 43     }
 44     void hashInsert(char * value) {
 45       int index = hashValue(value);
 46       cout<<"hello"<<endl;
 47       if (hashTable[index].key == NULL) {
 48         hashTable[index].key = new char [strlen(value) + 1];
 49         strncpy(hashTable[index].key, value, strlen(value));
 50         hashTable[index].key[strlen(value)] = '\0';
 51         hashTable[index].count = 1;
 52         return;
 53       } else if (strcmp(hashTable[index].key, value) == 0) {
 54         hashTable[index].count++;
 55         return;
 56       }
 57     }

 58     void output() {
 59       ofstream out;
 60       out.open("tt.txt");
 61       for (int i = 0; i < hashSize; i++) {
 62         if (hashTable[i].key) {
 63           out<<hashTable[i].key<<":"<<hashTable[i].count<<endl;
 64         }
 65       }
 66       out.close();
 67     }
 68 };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值