-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharraylist.c
More file actions
92 lines (74 loc) · 1.92 KB
/
arraylist.c
File metadata and controls
92 lines (74 loc) · 1.92 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
91
92
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "arraylist.h"
// ensure that definitions are consistent with header
#ifndef DEBUG
#define DEBUG 0
#endif
// create storage and initialize length/size
// returns 1 on success, 0 for failure
int al_init(arraylist_t *L, unsigned capacity)
{
L->data = (elem_t *) malloc(capacity * sizeof(elem_t));
if (L->data == NULL) return 0;
L->length = 0;
L->startingPoint = 0;
L->size = capacity;
return 1;
}
arraylist_t *al_create(unsigned capacity)
{
arraylist_t *L = malloc(sizeof(arraylist_t));
if (L == NULL) return NULL;
if (al_init(L, capacity)) {
return L;
}
free(L);
return NULL;
}
void al_destroy(arraylist_t *L)
{
//printf("DATA ISNDIE |%s|\n", *(L->data));
free(L->data);
free(L);
}
unsigned al_length(arraylist_t *L)
{
return L->length;
}
// add specified element to end of list
// returns 1 on success, 0 on failure
// assumes list has been initialized
int al_push(arraylist_t *L, elem_t elem)
{
// check whether array is full
if (L->size == L->length) {
// increase capacity
int new_size = L->size * 2;
elem_t *new_data = realloc(L->data, new_size * sizeof(elem_t));
if (new_data == NULL) return 0;
if (DEBUG) printf("Increased size to %d from %d\n", new_size, L->size);
L->size = new_size;
L->data = new_data;
}
L->data[L->length] = elem;
L->length++;
return 1;
}
// remove item from start of list
// write item to dest (if dest is non-NULL)
// return 1 on success, 0 on failure (i.e., list is empty)
int al_pop(arraylist_t *L, elem_t *dest)
{
if (L->length == 0)
return 0;
if (dest) {
L->length--;
*dest = L->data[L->startingPoint];
if (DEBUG) printf("Removed %s; new length %d\n", L->data[L->startingPoint], L->length);
L->startingPoint++;
return 1;
}
return 0;
}