113 lines
2.6 KiB
C
113 lines
2.6 KiB
C
#include <odweta/list.h>
|
|
#include <odweta/vector.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define init_error_exit(l) fprintf(stderr, "could not init list\n"); free(l); exit(EXIT_FAILURE)
|
|
|
|
list_t*
|
|
listInit() {
|
|
list_t* l = malloc(sizeof(list_t));
|
|
if (!l) {
|
|
init_error_exit(l);
|
|
}
|
|
|
|
l->data = (vector_t *)vectorInit(VECTOR);
|
|
if (!l->data) {
|
|
init_error_exit(l);
|
|
}
|
|
|
|
l->size = 0;
|
|
l->capacity = 1;
|
|
|
|
return l;
|
|
}
|
|
|
|
void
|
|
listPush(list_t* l, dataType_e type, void* element) {
|
|
vector_t* newVec;
|
|
switch (type) {
|
|
case INT:
|
|
newVec = vectorInit(INT);
|
|
vectorPush(newVec, element);
|
|
vectorPush((vector_t *)l->data, newVec);
|
|
break;
|
|
case FLOAT:
|
|
newVec = vectorInit(FLOAT);
|
|
vectorPush(newVec, element);
|
|
vectorPush((vector_t *)l->data, newVec);
|
|
break;
|
|
case CHAR:
|
|
newVec = vectorInit(CHAR);
|
|
vectorPush(newVec, element);
|
|
vectorPush((vector_t *)l->data, newVec);
|
|
break;
|
|
case VECTOR:
|
|
newVec = vectorInit(VECTOR);
|
|
vectorPush(newVec, element);
|
|
vectorPush((vector_t *)l->data, newVec);
|
|
break;
|
|
default:
|
|
perror("specify a valid vector type\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
l->size += 1;
|
|
if (l->size == l->capacity) {
|
|
l->capacity *= 2;
|
|
}
|
|
}
|
|
|
|
void
|
|
listPrint(list_t* l) {
|
|
fprintf(stdout, "[");
|
|
int i;
|
|
for (i = 0; i < l->size; i++) {
|
|
vector_t *ithVec = (vector_t *)vectorGetAt((vector_t *)l->data, i);
|
|
|
|
switch (ithVec->type) {
|
|
case INT:
|
|
printf("%d", *((int *)vectorGetAt(ithVec, 0)));
|
|
break;
|
|
case FLOAT:
|
|
printf("%f", *((float *)vectorGetAt(ithVec, 0)));
|
|
break;
|
|
case CHAR:
|
|
printf("'%c'", *((char *)vectorGetAt(ithVec, 0)));
|
|
break;
|
|
case VECTOR:
|
|
_printVectorRecursive(ithVec->data, 0);
|
|
break;
|
|
}
|
|
|
|
if (i < l->size - 1) {
|
|
fprintf(stdout, ", ");
|
|
}
|
|
}
|
|
fprintf(stdout, "]\n");
|
|
}
|
|
|
|
void
|
|
listCleanup(list_t* l) {
|
|
vectorCleanup((vector_t *)l->data);
|
|
free(l);
|
|
}
|
|
|
|
void*
|
|
listPop(list_t* l) {
|
|
if (l->size != 0) {
|
|
vector_t *first_ptr = (vector_t *)vectorPop((vector_t *)l->data);
|
|
void *ptr = vectorPop(first_ptr);
|
|
l->size -= 1;
|
|
|
|
if (l->size <= l->capacity / 2) l->capacity /= 2;
|
|
if (l->capacity == 0) l->capacity = 1;
|
|
|
|
return ptr;
|
|
} else {
|
|
// cannot pop when there is no value in the list
|
|
return NULL;
|
|
}
|
|
}
|