fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define HASHSIZE 101
  6.  
  7. static struct Nlist *hashtab[HASHSIZE]; // pointer table
  8.  
  9. struct Nlist {
  10. struct Nlist *next; // next entry in chain
  11. char *name; // defined name
  12. char *defn; // replacement text
  13. };
  14.  
  15. char *strdup(char *s)
  16. {
  17. char *tmp = malloc(strlen(s) + 1);
  18. if(tmp != NULL)
  19. strcpy(tmp, s);
  20. return tmp;
  21. }
  22.  
  23. unsigned hash(char *s)
  24. {
  25. unsigned hashval;
  26.  
  27. for(hashval = 0; *s != '\0'; s++)
  28. hashval = *s + 31 * hashval;
  29. return hashval % HASHSIZE;
  30. }
  31.  
  32. struct Nlist *lookup(char *s, struct Nlist **previous)
  33. {
  34. struct Nlist *np;
  35. int i = 0;
  36. *previous = NULL;
  37.  
  38. for(np = hashtab[hash(s)]; np != NULL; np = np->next, i++)
  39. if(strcmp(s, np->name) == 0)
  40. return np;
  41. if(i > 0)
  42. *previous = np;
  43.  
  44. return NULL;
  45. }
  46.  
  47. struct Nlist *install(char *name, char *defn)
  48. {
  49. struct Nlist *np;
  50. struct Nlist *tmp;
  51. unsigned hashval;
  52.  
  53. if((np = lookup(name, &tmp)) == NULL) {
  54. np = malloc(sizeof(*np));
  55. if(np == NULL || (np->name = strdup(name)) == NULL)
  56. return NULL;
  57. hashval = hash(name);
  58. np->next = hashtab[hashval];
  59. hashtab[hashval] = np;
  60. } else {
  61. free(np->defn);
  62. }
  63.  
  64. if((np->defn = strdup(defn)) == NULL)
  65. return NULL;
  66. return np;
  67. }
  68.  
  69. void printList(char *name)
  70. {
  71. for(struct Nlist *tmp = hashtab[hash(name)]; tmp != NULL; tmp = tmp->next) {
  72. printf("%s\n", tmp->name);
  73. }
  74. }
  75.  
  76. void undef(char *name)
  77. {
  78. struct Nlist *tmp = hashtab[hash(name)];
  79.  
  80. if(!strcmp(tmp->name, name)) { // delete the head node
  81. hashtab[hash(name)] = tmp->next;
  82. free(tmp->name);
  83. free(tmp);
  84.  
  85. return;
  86. }
  87.  
  88. for(; strcmp(tmp->next->name, name); tmp = tmp->next)
  89. ;
  90.  
  91. struct Nlist *save = tmp->next; // save the desired node for deletion
  92. tmp->next = tmp->next->next; // adjust the links
  93. free(save->name);
  94. free(save);
  95. }
  96.  
  97.  
  98. int main()
  99. {
  100. install("test", "11");
  101. install("estt", "qwe");
  102. install("tset", "2323");
  103. //undef("test");
  104.  
  105. undef("test");
  106. printList("test");
  107.  
  108. return 0;
  109. }
  110.  
  111.  
Success #stdin #stdout 0s 2420KB
stdin
Standard input is empty
stdout
Standard output is empty