109 lines
2.8 KiB
C
109 lines
2.8 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:
|
|
// Instead of reallocating memory for vector_t pointers, allocate memory for the vector data
|
|
if (l->size == 0) {
|
|
// Allocate memory for the vector data for the first time
|
|
l->data = malloc(sizeof(vector_t) * l->capacity);
|
|
} else {
|
|
// Reallocate memory for the vector data
|
|
l->data = realloc((vector_t *)l->data, sizeof(vector_t) * l->capacity);
|
|
}
|
|
if (!l->data) {
|
|
perror("failed to allocate memory for vector data\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
// Copy the vector data from the element to the vector
|
|
memcpy((vector_t *)(l->data) + l->size, (vector_t *)element, sizeof(vector_t));
|
|
|
|
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((vector_t *)l->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);
|
|
}
|