Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222285
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-07-11 10:33:54

2.9 Hash Tables

Hash tables are one of the great inventions of computer science. They combine arrays, lists, and some mathematics to create an efficient structure for storing and retrieving dynamic data.
The typical application is a symbol table, which associates some value (the data) with each member of a dynamic set of strings (the keys).


  1. /**
  2.   tpop(2):Algorithm and Data Structure,
  3.   created on Jul 11, 2011
  4.   */

  5. #include <stdio.h>
  6. enum {
  7.     NHASH = 1024,
  8.     MULTIPLIER = 31
  9. };
  10. typedef struct Nameval Nameval;
  11. struct Nameval {
  12.     char *name;
  13.     int value;
  14.     Nameval *next; /* in chain */
  15. };
  16. Nameval *symtab[NHASH]; /* a symbol table */

  17. unsigned int hash(char *);

  18. /* lookup: find name in symtab, with optional create */
  19. Nameval* lookup (char *name, int create, int value)
  20. {
  21.     int h;
  22.     Nameval *sym;

  23.     h = hash(name);
  24.     for (sym = symtab[h]; sym != NULL; sym = sym->next)
  25.       if (strcmp(name, sym->name == 0))
  26.     return sym;
  27.     if (create == 1) {
  28.     sym = (Nameval *)malloc(sizeof(Nameval));
  29.     sym->name = name; /* assumed allocated elsewhere */
  30.     sym->value = value;
  31.     sym->next = symtab[h];
  32.     symtab[h] = sym;
  33.     }
  34.     return sym;
  35. }


  36. /* hash: compute hash value of string */
  37. unsigned int hash(char *str)
  38. {
  39.     unsigned int h;
  40.     unsigned char *p;

  41.     h = 0;
  42.      for (p = (unsigned char *)str; *p != '\0'; p++)
  43.        h = MULTIPLIER * h + *p;
  44.      return h % NHASH;
  45. }

  46. int main (int argc, char* argv[]) {
  47.  Nameval *item ;
  48.  lookup("mark", 1, 101);
  49.  lookup("ht", 1, 102);
  50. lookup("tao", 1, 101);
  51. item = lookup("mht",1, 10);
  52.     printf("The value of name %s is %d\n", item->name, item->value);
  53. }

阅读(486) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~