|
1 | 1 | #include <stdlib.h> |
2 | 2 | #include <string.h> |
3 | 3 | #include <assert.h> |
4 | | - |
5 | 4 | #include "arraylist.h" |
6 | 5 |
|
7 | | -const int DEFAULT_CAPACITY = 10; |
| 6 | +#define ARRAYLIST_DEAUFALT_SIZE 4 |
8 | 7 |
|
9 | 8 | /** |
10 | 9 | * create a new empty arraylist |
11 | 10 | */ |
12 | 11 | ArrayList *listCreate() { |
13 | 12 | ArrayList *list = malloc(sizeof(ArrayList)); |
| 13 | + |
| 14 | + list->dataStore = malloc(sizeof(void *) * ARRAYLIST_DEAUFALT_SIZE); |
| 15 | + assert(list->dataStore); |
14 | 16 | list->theSize = 0; |
15 | | - list->dataStore = malloc(sizeof(void *) * DEFAULT_CAPACITY); |
| 17 | + list->capacity = ARRAYLIST_DEAUFALT_SIZE; |
16 | 18 |
|
17 | 19 | list->size = listSize; |
| 20 | + list->get = listGet; |
| 21 | + list->set = listSet; |
| 22 | + list->append = listAppend; |
18 | 23 |
|
19 | 24 | return list; |
20 | 25 | } |
21 | 26 |
|
| 27 | +void listIsRealloc(ArrayList *list) { |
| 28 | + if (list->theSize == list->capacity) { |
| 29 | + unsigned int newCapa = list->capacity * 2; |
| 30 | + list->capacity = newCapa; |
| 31 | + list->dataStore = realloc(list->dataStore, sizeof(void *) * newCapa); |
| 32 | + assert(list->dataStore); |
| 33 | + } |
| 34 | +} |
| 35 | + |
22 | 36 | int listSize(ArrayList *list) { |
23 | 37 | return list->theSize; |
24 | 38 | } |
25 | 39 |
|
| 40 | +void *listGet(ArrayList *list, unsigned int index) { |
| 41 | + assert(index < list->theSize); |
| 42 | + return list->dataStore[index]; |
| 43 | +} |
| 44 | + |
| 45 | +void listSet(ArrayList *list, unsigned int index, void *value) { |
| 46 | + assert(index < list->theSize); |
| 47 | + list->dataStore[index] = value; |
| 48 | +} |
| 49 | + |
| 50 | +void listAppend(ArrayList *list, void *value) { |
| 51 | + listIsRealloc(list); |
| 52 | + list->dataStore[list->theSize++] = value; |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | + |
26 | 58 |
|
27 | 59 |
|
0 commit comments