-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayList.c
More file actions
90 lines (78 loc) · 2.3 KB
/
Copy pathArrayList.c
File metadata and controls
90 lines (78 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "ArrayList.h"
//create a new list with a initial capacity
ArrayList* createArrayList(int capacity) {
ArrayList* list = malloc(sizeof(ArrayList));
if (list == NULL) {
fprintf(stderr, "unable to allocate memory\n");
exit(1);
}
list->arr = malloc(capacity * sizeof(void*));
if (list->arr == NULL) {
fprintf(stderr, "unable to allocate memory\n");
free(list);
exit(1);
}
list->size = 0;
list->capacity = capacity;
return list;
}
//add element to list
void addToArrayList(ArrayList* list, void* val) {
if (list->size == list->capacity) { //if at capacity double capacity of list
void** newArr = realloc(list->arr, list->capacity * 2 * sizeof(void*));
if (newArr == NULL) {
fprintf(stderr, "unable to allocate memory\n");
exit(1);
}
list->arr = newArr;
list->capacity *= 2;
}
list->arr[list->size] = val; //assign element
list->size++;
}
//remove element at index and shift elements left
void removeFromArrayList(ArrayList* list, int idx) {
if (idx < 0 || idx >= list->size) {
fprintf(stderr, "index out of bounds\n");
exit(1);
}
//shift elements left to fill the gap
for (int i = idx; i < list->size - 1; i++) {
list->arr[i] = list->arr[i + 1];
}
list->size--;
//reduce capacity if too much unused space
if (list->size > 0 && list->size <= list->capacity / 4) {
void** newArr = realloc(list->arr, (list->capacity / 2) * sizeof(void*));
if (newArr != NULL) { //only shrink if realloc succeeds
list->arr = newArr;
list->capacity /= 2;
}
}
}
//return element at index
void* getFromArrayList(ArrayList* list, int idx) {
if (idx < 0 || idx >= list->size) {
fprintf(stderr, "index out of bounds\n");
exit(1);
}
return list->arr[idx];
}
//set element at index
void setArrayList(ArrayList* list, int idx, int val) {
if (idx < 0 || idx >= list->size) {
fprintf(stderr, "index out of bounds\n");
exit(1);
}
list->arr[idx] = (void*)(intptr_t)val;
}
//free list
void freeArrayList(ArrayList* list) {
if (list != NULL) {
free(list->arr);
free(list);
}
}