learning-cc4e

Solution to https://cc4e.com/. If you copy these you're not right in the head.
git clone https://kaka.farm/~git/learning-cc4e
Log | Files | Refs

solution.c (1276B)


      1 void __Map_put(struct Map* self, char *key, int value) {
      2   struct MapEntry *old, *new;
      3   char *new_key;
      4   if ( key == NULL ) return;
      5 
      6   old = __Map_find(self, key);
      7   if ( old != NULL ) {
      8     old->value = value;
      9     return;
     10   }
     11 
     12   new = malloc(sizeof(*new));
     13 
     14   new_key = malloc(sizeof(char) * (strlen(key) + 1));
     15   new_key = strcpy(new_key, key);
     16   new->key = new_key;
     17   new->value = value;
     18   new->__prev = NULL;
     19   new->__next = NULL;
     20 
     21   if (self->__head == NULL) {
     22     self->__head = new;
     23     self->__tail = new;
     24   } else {
     25     self->__tail->__next = new;
     26     new->__prev = self->__tail;
     27     self->__tail = new;
     28   }
     29 
     30   self->__count++;
     31 }
     32 
     33 int __Map_size(struct Map* self)
     34 {
     35   struct MapEntry *curr;
     36   int count = 0;
     37 
     38   for (curr = self->__head;
     39        curr != NULL;
     40        curr = curr->__next) {
     41     ++count;
     42   }
     43 
     44   return count;
     45 }
     46 
     47 int __Map_get(struct Map* self, char *key, int def)
     48 {
     49   struct MapEntry *curr = __Map_find(self, key);
     50 
     51   if (curr == NULL) {
     52     return def;
     53   } else {
     54     return curr->value;
     55   }
     56 }
     57 
     58 struct Map * Map_new() {
     59   struct Map *p = malloc(sizeof(*p));
     60 
     61   p->__head = NULL;
     62   p->__tail = NULL;
     63   p->__count = 0;
     64 
     65   p->put = &__Map_put;
     66   p->get = &__Map_get;
     67   p->size = &__Map_size;
     68   p->dump = &__Map_dump;
     69   p->del = &__Map_del;
     70 
     71   return p;
     72 }