Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <limits.h>
- #include <string.h>
- struct entry_s {
- char *key;
- float value;
- struct entry_s *next;
- };
- typedef struct entry_s entry_t;
- typedef struct {
- int size;
- entry_t **tbl;
- } hashtable_t;
- /* Hash a string for a particular hash table. */
- static int
- ht_hash (hashtable_t * ht, const char *key)
- {
- unsigned long int hashval = 0;
- int len, i = 0;
- /* Convert our string to an integer */
- len = strlen (key);
- while (hashval < ULONG_MAX && i < len)
- {
- hashval = hashval << 8;
- hashval += key[i];
- i++;
- }
- return hashval % ht->size;
- }
- /* Create a key-value pair. */
- static entry_t *
- ht_newpair (const char *key, float value)
- {
- entry_t *pair = NULL;
- if ((pair = (entry_t *) malloc (sizeof (entry_t))) != NULL)
- {
- pair->key = strdup (key);
- pair->value = value;
- pair->next = NULL;
- }
- return pair;
- }
- /* Create a new hashtable. */
- hashtable_t *
- ht_create (int size)
- {
- hashtable_t *ht = NULL;
- int i;
- if (size < 1)
- return NULL;
- /* Allocate the table itself. */
- if ((ht = (hashtable_t *) malloc (sizeof (hashtable_t))) != NULL)
- {
- /* Allocate pointers to the head nodes. */
- if ((ht->tbl = (entry_t **) malloc (sizeof (entry_t *) * size)) == NULL)
- {
- free (ht);
- return NULL;
- }
- for (i = 0; i < size; i++)
- ht->tbl[i] = NULL;
- ht->size = size;
- }
- return ht;
- }
- /* Insert a key-value pair into a hash table. */
- void
- ht_set (hashtable_t *ht, const char *key, float value)
- {
- int bin = 0;
- entry_t *next = NULL;
- entry_t *last = NULL;
- if (ht == NULL)
- return;
- bin = ht_hash (ht, key);
- next = ht->tbl[bin];
- /* Looking for existing key */
- while (next)
- {
- if (next->key && strcmp (key, next->key) == 0)
- {
- next->value = value;
- return;
- }
- last = next;
- next = last->next;
- }
- /* Not found, appending */
- next = ht_newpair (key, value);
- if (last)
- last->next = next;
- else
- ht->tbl[bin] = next;
- }
- /* Retrieve a value from a hash table. */
- float
- ht_get (hashtable_t *ht, const char *key)
- {
- int bin = 0;
- entry_t *pair;
- if (ht == NULL)
- return 0.0;
- bin = ht_hash (ht, key);
- /* Step through the bin, looking for our value. */
- pair = ht->tbl[bin];
- while (pair)
- {
- if (pair->key && strcmp (key, pair->key) == 0)
- return pair->value;
- pair = pair->next;
- }
- return 0.0;
- }
- /* Release memory */
- void
- ht_delete (hashtable_t *ht)
- {
- int i;
- if (ht == NULL)
- return;
- for (i = 0; i > ht->size; i++)
- {
- entry_t *pair = ht->tbl[i];
- while (pair)
- {
- entry_t *next = pair->next;
- free (pair->key);
- free (pair);
- pair = next;
- }
- }
- free (ht->tbl);
- free (ht);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement