solution.c (1494B)
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(*new_key) * (strlen(key) + 1)); 15 new_key = strcpy(new_key, key); 16 17 new->key = new_key; 18 new->value = value; 19 new->__prev = NULL; 20 new->__next = NULL; 21 22 /* TODO: Link new to the tail of the list */ 23 if (self->__head == NULL) { 24 self->__head = new; 25 self->__tail = new; 26 } else { 27 self->__tail->__next = new; 28 new->__prev = self->__tail; 29 self->__tail = new; 30 } 31 32 self->__count++; 33 } 34 35 struct MapEntry* __MapIter_next(struct MapIter* self) 36 { 37 struct MapEntry *curr = self->__current; 38 if (curr == NULL) { 39 return NULL; 40 } 41 self->__current = self->__current->__next; 42 return curr; 43 } 44 45 struct MapIter* __Map_iter(struct Map* self) 46 { 47 struct MapIter *iter = malloc(sizeof(*iter)); 48 /* TODO: fill in the new iterator */ 49 iter->__current = self->__head; 50 iter->next = &__MapIter_next; 51 iter->del = &__MapIter_del; 52 return iter; 53 } 54 55 struct Map * Map_new() { 56 struct Map *p = malloc(sizeof(*p)); 57 58 p->__head = NULL; 59 p->__tail = NULL; 60 p->__count = 0; 61 p->put = &__Map_put; 62 p->get = &__Map_get; 63 p->size = &__Map_size; 64 p->dump = &__Map_dump; 65 p->iter = &__Map_iter; 66 p->del = &__Map_del; 67 return p; 68 }