码迷,mamicode.com
首页 > 其他好文 > 详细

哈希表

时间:2015-01-29 12:25:50      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

  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. }





附件列表

     

    哈希表

    标签:

    原文地址:http://www.cnblogs.com/sober-reflection/p/1358457bd8be9d91c59609915728d28a.html

    (0)
    (0)
       
    举报
    评论 一句话评论(0
    登录后才能评论!
    © 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
    迷上了代码!