#include #include //#include "stringVec.h" struct node { struct node* next; char* key; }; struct stringVec { struct node* head; }; void sv_print(struct stringVec* v); struct stringVec * sv_init (); int sv_size (struct stringVec *v); int sv_add (struct stringVec* v, char* s); char* sv_get (struct stringVec* v, int idx); void sv_remove (struct stringVec* v, int idx); void clear (struct node* n); struct node* findLast (struct node* n); struct stringVec * sv_init(){ struct stringVec *v = (struct stringVec*) malloc (sizeof (struct stringVec)); v->head = NULL; return v; } int sv_size (struct stringVec* v){ int size = 0; struct node* n = v->head; while (n){ n = n->next; size ++; } return size; } int sv_add (struct stringVec* v, char* s){ int size = sv_size(v); struct node* n; struct node* n2 = (struct node*) malloc (sizeof(struct node)); n2->next = NULL; n2->key = s; if (v->head == NULL) v->head = n2; else{ n = v->head; while (n->next != NULL) n = n->next; n->next = n2; } return (size-1); } char* sv_get (struct stringVec* v, int idx){ struct node* n = v->head; int i; int size = sv_size(v); if (idx < size){ for (i = 0; i < idx; i ++) n = n->next; return (n->key); } return NULL; } void sv_print(struct stringVec* v){ struct node *f = v->head; while(f){ printf("'%s' ^ %p -> %p :: ",f->key,f,f->next); f=f->next; } printf("\n"); } void sv_remove (struct stringVec* v, int idx){ struct node* n = v->head; struct node* m; int i; int size = sv_size(v); printf("DELETE SIZE: %d\n"); sv_print(v); if (idx < size){ for (i = 0; i < idx-1; i ++) n = n->next; m = n->next; if(n->next){ n->next = m->next; printf("####### freeing :[%d] '%s' %p %d\n",size,m->key, m, sv_size(v)); fflush(stdout); free (m); }else{ printf(">>>>>>> freeing :[%d] '%s' %p %d\n",size,n->key, n, sv_size(v)); free(n); v->head = NULL; } } } void clear (struct node* n){ if (n->next == NULL) free (n); else clear (n->next); } struct node* findLast (struct node* n){ if (n == NULL) return n; return (findLast (n->next)); } int main() { char a[6] = "Hello"; struct stringVec *v = sv_init(); printf("%d\n", sv_size(v)); // outputs: 0 printf("%d\n", sv_add(v, "First string")); // outputs: 0 printf("%d\n", sv_add(v, "Second string")); // outputs: 1 printf("%d\n", sv_add(v, "Third string")); // outputs: 2 printf("%d\n", sv_size(v)); // outputs: 3 printf("%s\n", sv_get(v, 1)); // outputs: Second string sv_remove(v, 1); printf("%s\n", sv_get(v, 1)); // outputs: Third string printf("%d\n", sv_size(v)); // outputs: 2 sv_add(v, a); a[2] = '$'; printf("---> %s\n", sv_get(v, 2)); // outputs: Hello printf("---> %s\n", a); // outputs: He$lo sv_remove(v, 0); // removes one element sv_remove(v, 0); // removes one element sv_remove(v, 0); // removes one element sv_remove(v, 0); // nothing happens, the data structure is empty printf("%d\n", sv_size(v)); // outputs: 0 sv_print(v); return 0; }