euler/c/int_list.c

83 lines
1.4 KiB
C
Raw Normal View History

2016-09-02 23:58:42 +00:00
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "int_list.h"
void int_list_init(int_list *l) {
l->data = NULL;
l->size = 0;
l->count = 0;
}
int int_list_count(int_list *l) {
return l->count;
}
void int_list_add(int_list *l, int value) {
if (l->size == 0) {
l->size = 10;
l->data = malloc(sizeof(int*) * l->size);
memset(l->data, '\0', sizeof(int*) * l->size);
}
if (l->size == l->count) {
l->size *= 2;
l->data = realloc(l->data, sizeof(int*) * l->size);
}
l->data[l->count] = value;
l->count++;
}
int int_list_get(int_list *l, int index) {
if (index >= l->count) {
printf("error: index out of range");
return 0;
}
return l->data[index];
}
void int_list_set(int_list *l, int index, int value) {
if (index >= l->count) {
printf("error: index out of range");
return;
}
l->data[index] = value;
}
void int_list_delete(int_list *l, int index) {
if (index >= l->count) {
printf("error: index out of range");
return;
}
int j = index;
for (int i = index; i < l->count; i++) {
l->data[j] = l->data[i];
j++;
}
l->count--;
}
int int_list_sum(int_list *l) {
int sum = 0;
for (int i = 0; i < l->count; i++) {
sum += (l->data[i]);
}
return sum;
}
void int_list_print(int_list *l) {
for (int i = 0; i < l->count; i++) {
printf("%d ", (l->data[i]));
}
printf("\n");
}
void int_list_free(int_list *l) {
free(l->data);
}