codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
#include <string.h> #include <stdio.h> #include <stdlib.h> #ifndef LIBDICTIONARY_H__ #define LIBDICTIONARY_H__ typedef struct _dictionary_t { char *key, *value; struct _dictionary_t *next; } dictionary_t; #endif int dictionary_init(dictionary_t *d) { if(d==NULL) return -1; d->key = "keykeykeykey"; d->value = "valuevalue"; d->next = NULL; return 0; } int dictionary_add(dictionary_t *d, char *key, char *value) { if(d->next != NULL) { if(strcmp(d->key, key) == 0) return -1; else return dictionary_add(d->next, key, value); } else { int k = strlen(key); int v = strlen(value); d->key = malloc(k*sizeof(char)); d->value = malloc(k*sizeof(char)); strcpy(d->key, key); strcpy(d->value, value); dictionary_t *d1 = (dictionary_t*)malloc(sizeof(dictionary_t)); dictionary_init(d1); d->next = d1; } return 0; } void dictionary_remove(dictionary_t *d, char *key) { dictionary_remover(d->next, key); } void dictionary_remover(dictionary_t *d, char *key) { if(d->next != NULL) { if(strcmp(d->next->key,key) != 0) dictionary_remove(d->next, key); else { free(d->next->key); free(d->next->value); d->next->key = NULL; d->next->value = NULL; dictionary_t *tmp = d->next; d->next = d->next->next; free(tmp); } } else if(strcmp(d->key, key) == 0) dictionary_destroy(d); } int dictionary_parse(dictionary_t *d, char *key_value) { char *value = strchr(key_value, ':'); while(key_value[i] != ':') { i++; } char *key=malloc(i*sizeof(char)); int i=0; strncpy(key, key_value, i); key[i] = '\0'; value = strchr(value, value[2]); return dictionary_add(d, key, value); } void dictionary_print(dictionary_t *d) { if(d->next != NULL) { printf("%s: %s", d->key, d->value); dictionary_print(d->next); } } void dictionary_destroy(dictionary_t *d) { dictionary_destroyer(d->next); } void dictionary_destroyer(dictionary_t *d) { if(d->next != NULL) { dictionary_remove(d, d->next->key); dictionary_destroy(d->next); } else { free(d->key); free(d->value); d->key = NULL; d->value = NULL; free(d); d = NULL; } } int main (void) { dictionary_t *d = (dictionary_t*)malloc(sizeof(dictionary_t)); dictionary_init(d); dictionary_parse(d, "Hi: Hey"); dictionary_print(d); dictionary_remove(d, "Hi"); dictionary_print(d); }
Private
[
?
]
Run code