C带有字符串键的哈希表。所有键是文件中的最后一个字符串

时间:2018-09-18 22:27:59

标签: c hashtable

我正在尝试使用字符串键实现哈希表。我不在乎这些值,因此它们是1的整数。我需要散列查找的速度,因此数组中没有二进制搜索。我的密钥字符串未正确存储,在插入时会按预期打印,但是当我显示哈希表的内容时,密钥都是文件中的最后一个条目。

请帮助

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

#define SIZE 103141 * 2
#define MAXCHAR 1000


struct DataItem {
   int data;   
   char* key;
};

struct DataItem* hashArray[SIZE]; 


unsigned long 
hashCode(char *key) {
   unsigned long hash = 5381;
   int c;
   while (c = *key++){
      hash = ((hash <<5)+ hash)+c; 
   }
   return hash % SIZE;
}

struct DataItem *search(char *key) {
   unsigned long hashIndex = hashCode(key);  

   //move in array until an empty 
   while(hashArray[hashIndex] != NULL) {
      if(hashArray[hashIndex]->key == key){ return hashArray[hashIndex]; }
      //go to next cell
      ++hashIndex;
      //wrap around the table
      hashIndex %= SIZE;
   }        

   return NULL;        
}

void insert(char* key,int data) {

   struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));
   item->data = data;  
   item->key = key;
   unsigned long hashIndex = hashCode(key);

   //move in array until an empty or deleted cell
   while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != NULL) {
      //go to next cell
      ++hashIndex;
      //wrap around the table
      hashIndex %= SIZE;
   }

   // this statement below prints the keys correctly 
   printf("%d  %s   %d\n",hashIndex,item->key,item->data);

   hashArray[hashIndex] = item;
}

void display() {
   int i = 0;

   for(i = 0; i<SIZE; i++) {

      if(hashArray[i] != NULL)
         // here the keys are all "S-4TNKZ"
         printf(" (%s,%d)\n",hashArray[i]->key,hashArray[i]->data);

     else
         printf(" .. \n");
   }

}

int main() {
   struct DataItem* item;

   char *probefile = "cychp_pruned_r2_0.1.ids.txt";

   FILE *probef; char str[MAXCHAR]; char *p; char *probe_name; 

   probef = fopen(probefile,"r");


   while (fgets(str, MAXCHAR, probef) != NULL){

      p = strtok(str,"\n");

      insert(p,1);
   }


   display();
   // this exists in the file 
   char *probe = "S-4TNIU";

   // if I insert it here, it works
   //insert(probe,1);

   // not found
   item = search(probe);

   if(item != NULL) {
      printf("Element found:%s %d\n", probe,item->data);
   } else {
      printf("Element not found [%s]\n",probe);
   }

}

0 个答案:

没有答案