I ACCEPT!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node {
char *str;
int val;
struct node *next;
};
static struct node *tab[2048];
static unsigned int hash(const char *str)
{
enum { MULTIPLIER = 31 };
unsigned int h = 0;
while (*str)
h = MULTIPLIER * h + (unsigned char) *str++;
return h % (sizeof tab / sizeof tab[0]);
}
static struct node *install(struct node *np)
{
unsigned int h;
np->next = tab[(h = hash(np->str))];
tab[h] = np;
return np;
}
static struct node *lookup(const char *str)
{
struct node *np;
for (np = tab[hash(str)]; np && strcmp(str, np->str); np = np->next)
;
return np;
}
static struct node *new(const char *str)
{
struct node *v;
if (!(v = malloc(sizeof *v)) || !(v->str = malloc(strlen(str) + 1)))
exit(EXIT_FAILURE);
strcpy(v->str, str);
v->val = 1;
return v;
}
static void print(struct node *const *tab, size_t n)
{
struct node *tp;
while (n--)
for (tp = *tab++; tp; tp = tp->next)
printf("%d %s\n", tp->val, tp->str);
}
int main(void)
{
struct node *ptr;
char buf[2048];
while (scanf("%2047s", buf) == 1)
if (!(ptr = lookup(buf)))
install(new(buf));
else
ptr->val++;
print(tab, sizeof tab / sizeof tab[0]);
return 0;
}