首页 > 代码库 > 哈希表

哈希表

  1. #define TABLE_SIZE 200003
  2. struct Node
  3. {
  4. char key[12], value[12];
  5. bool flag;
  6. Node () { flag = false; }
  7. } table[TABLE_SIZE];
  8. unsigned int BKDRHash(char *key)
  9. {
  10. unsigned int seed = 131;
  11. unsigned int hash = 0;
  12. while (*key)
  13. {
  14. hash = hash * seed + (*key++);
  15. }
  16. return (hash & 0x7FFFFFFF) % TABLE_SIZE;
  17. }
  18. int insert(char *key,char *value){
  19. //return 1 means OVERWRITE
  20. int pos = BKDRHash(key), m = 0,ret=0;
  21. while (table[pos].flag ) {//has word
  22. if(strcmp(table[pos].key, key) == 0){
  23. ret=1;//key match,OVER_WRITE
  24. break;
  25. }
  26. pos += 2 * (++m) - 1;
  27. if (pos >= TABLE_SIZE) pos -= TABLE_SIZE;
  28. }
  29. if(1!=ret){//over write no need this
  30. strcpy (table[pos].key, key);
  31. }
  32. strcpy (table[pos].value, value);
  33. table[pos].flag = true;//mark that has word
  34. return ret;
  35. }
  36. char* find(char* key){
  37. int pos = BKDRHash(key), m = 0;
  38. while (table[pos].flag) {
  39. if (strcmp(table[pos].key, key) == 0) {
  40. return table[pos].value;
  41. }
  42. else {
  43. pos += 2 * (++m) - 1;
  44. pos = (pos >= TABLE_SIZE ? pos - TABLE_SIZE : pos);
  45. }
  46. }
  47. return NULL;
  48. }



来自为知笔记(Wiz)


附件列表

     

    哈希表