mirror of
https://github.com/theoludwig/libcproject.git
synced 2025-05-21 23:21:15 +02:00
39
lib/array_list.c
Normal file
39
lib/array_list.c
Normal file
@ -0,0 +1,39 @@
|
||||
#include "array_list.h"
|
||||
|
||||
struct array_list* array_list_initialization() {
|
||||
struct array_list* list = malloc(sizeof(struct array_list));
|
||||
list->data = malloc(sizeof(void*) * ARRAY_LIST_INITIAL_CAPACITY);
|
||||
list->size = 0;
|
||||
list->capacity = ARRAY_LIST_INITIAL_CAPACITY;
|
||||
return list;
|
||||
}
|
||||
|
||||
void array_list_add(struct array_list* list, void* element) {
|
||||
if (list->size >= list->capacity) {
|
||||
size_t previous_capacity = list->capacity;
|
||||
list->capacity += ARRAY_LIST_INITIAL_CAPACITY;
|
||||
list->data = realloc(list->data, sizeof(void*) * list->capacity);
|
||||
for (size_t index = previous_capacity; index < list->capacity; index++) {
|
||||
list->data[index] = NULL;
|
||||
}
|
||||
}
|
||||
list->data[list->size] = element;
|
||||
list->size++;
|
||||
}
|
||||
|
||||
void array_list_remove(struct array_list* list, size_t index) {
|
||||
if (index >= list->size) {
|
||||
return;
|
||||
}
|
||||
for (size_t i = index + 1; i < list->size - 1; i++) {
|
||||
list->data[i - 1] = list->data[i];
|
||||
}
|
||||
list->size--;
|
||||
}
|
||||
|
||||
void* array_list_get(struct array_list* list, size_t index) {
|
||||
if (index >= list->size) {
|
||||
return NULL;
|
||||
}
|
||||
return list->data[index];
|
||||
}
|
25
lib/array_list.h
Normal file
25
lib/array_list.h
Normal file
@ -0,0 +1,25 @@
|
||||
#ifndef __ARRAY_LIST__
|
||||
#define __ARRAY_LIST__
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "linked_list.h"
|
||||
|
||||
#define ARRAY_LIST_INITIAL_CAPACITY 10
|
||||
|
||||
struct array_list {
|
||||
void** data;
|
||||
size_t size;
|
||||
size_t capacity;
|
||||
};
|
||||
|
||||
struct array_list* array_list_initialization();
|
||||
|
||||
void array_list_add(struct array_list* list, void* element);
|
||||
|
||||
void array_list_remove(struct array_list* list, size_t index);
|
||||
|
||||
void* array_list_get(struct array_list* list, size_t index);
|
||||
|
||||
#endif
|
Reference in New Issue
Block a user