Skip to content

Instantly share code, notes, and snippets.

@shkesar
Created September 22, 2016 08:37
Show Gist options
  • Save shkesar/9ae14dbf60642b94052da4138b98b8a2 to your computer and use it in GitHub Desktop.
Save shkesar/9ae14dbf60642b94052da4138b98b8a2 to your computer and use it in GitHub Desktop.
Hash table done in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hashtable.h"
struct nlist *hashtab[HASHSIZE];
unsigned hash(char *s) {
unsigned hashval = 0;
while(*s) hashval += *s++;
return hashval % HASHSIZE;
}
struct nlist *lookup(char *key) {
for (struct nlist *p = hashtab[hash(key)]; p != NULL; p = p->next)
if(strcmp(key, p->key) == 0)
return p;
return NULL;
}
struct nlist *install(char* key, int value) {
struct nlist *p;
if ((p = lookup(key)) == NULL) {
p = malloc(sizeof(struct nlist));
unsigned hashval = hash(key);
p->key = strdup(key);
p->value = value;
p->next = hashtab[hashval];
hashtab[hashval] = p;
} else {
p->value = value;
}
return p;
}
#ifndef _HASHTABLE_H_
#define _HASHTABLE_H_ TRUE
#define HASHSIZE 100
struct nlist {
struct nlist *next;
char* key;
int value;
};
unsigned hash(char *s);
struct nlist *lookup(char *key);
struct nlist *install(char* key, int value);
#endif
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "hashtable.h"
int main(int argc, char const *argv[])
{
install("aa", 5);
install("aggarwal", 2);
install("b", 7);
struct nlist *n = lookup("b");
assert (n->value == 7);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment