forked from batiste/sdl2-opengl-es
-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
112 lines (101 loc) · 2.75 KB
/
list.c
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdlib.h>
void assert(int value) {
if(value)
return;
printf("assert fail\n");
exit(1);
}
//Generic list Element
struct ListElement {
struct ListElement *next;
struct ListElement *prev;
void *data;
};
typedef struct ListElement ListElement;
//Generic List Structure
struct GenericList {
int length; //Number of elements in list
struct ListElement *first; //Ptr to first element in list
struct ListElement *last; //Ptr to last element in list
};
typedef struct GenericList GenericList;
void createList(struct GenericList *list) {
list->length = 0;
list->first = NULL;
list->last = NULL;
}
ListElement *addToList(GenericList *list, void *item) {
//check inputs
assert(item!=NULL);
assert(list!=NULL);
//Create generic element to hold item ptr
ListElement *newElement;
newElement = (ListElement *)malloc(sizeof(newElement)); //create generic element
assert(newElement != NULL);
list->length = list->length + 1;
newElement->data = item;
if (list->length == 1)
{
list->last = newElement;
newElement->prev = NULL;
newElement->next = NULL;
}
else
{
newElement->prev = NULL;
newElement->next = list->first;
list->first->prev = newElement;
}
list->first = newElement;
return newElement;
}
int removeFromList(GenericList *list, ListElement *toRemove) {
// TODO: find a mechanisms to free deleted items
//check inputs
if(toRemove==NULL) {
return 0;
}
assert(list!=NULL);
ListElement *el;
if (list->length == 0) {
return 0;
}
if (list->length == 1) {
if(toRemove == list->first) {
list->length = 0;
list->first = NULL;
list->last = NULL;
return 1;
}
return 0;
}
// there is at least 2 items in the list
for(el = list->first; el != NULL; el=el->next) {
// found a matching item
if(el == toRemove) {
// this is the first item
if(el == list->first) {
list->first = el->next;
list->first->prev = NULL;
// this is the last item
} else if (el == list->last) {
list->last = el->prev;
list->last->next = NULL;
} else {
el->prev->next = el->next;
el->next->prev = el->prev;
}
list->length = list->length - 1;
return 1;
}
}
return 0;
}
void displayList(GenericList *list) {
ListElement *el;
printf("List length %d\n", list->length);
int i = 1;
for(el = list->first; el != NULL; el=el->next, i=i+1) {
printf("Item %d address %d\n", i, (int)el->data);
}
}