rendered paste body#include <stdio.h>
#include <stdlib.h>
//#include "stringVec.h"
struct node {
struct node* next;
char* key;
};
struct stringVec {
struct node* head;
};
void sv_init (struct stringVec* v);
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);
void sv_init (struct stringVec* v){
v = (struct stringVec*) malloc (sizeof (struct stringVec));
v->head = NULL;
}
int sv_size (struct stringVec* v){
int size = 0;
struct node* n = v->head;
while (n != NULL){
size ++;
n = n->next;
}
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->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_remove (struct stringVec* v, int idx){
struct node* n = v->head;
struct node* m;
int i;
int size = sv_size(v);
if (idx < size){
for (i = 0; i < idx-1; i ++)
n = n->next;
m = n->next;
n->next = m->next;
free (m);
}
}
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(&v);
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
return 0;
}