-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.c
More file actions
72 lines (60 loc) · 1.36 KB
/
Copy pathlist.c
File metadata and controls
72 lines (60 loc) · 1.36 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
#include <stdlib.h>
#include <stdio.h>
#include "list.h"
// Adds an object to the beginning of the list
void list_add(List* list, void* object) {
Item* item = malloc(sizeof(Item));
item->object = object;
item->next = list->start;
if(!list->start) {
list->current = item;
}
list->start = item;
}
// Removes an object from the list.
void list_remove(List* list, void* object) {
Item* item = NULL;
Item* prevItem = NULL;
for(item = list->start; item->object != object && item != NULL; item = item->next) {
prevItem = item;
}
if(!item) {
fprintf(stderr, "Tried to remove item that doesn't exist from list\n");
exit(1);
}
if(prevItem) {
prevItem->next = item->next;
}
else {
list->start = item->next;
}
free(item);
}
// Returns the next object in the list, or NULL if end of list reached.
void* list_next(List* list) {
void* object = NULL;
if(list->current) {
object = list->current->object;
list->current = list->current->next;
}
else {
list->current = list->start;
object = NULL;
}
return object;
}
// Instantiates and returns new list
List* list_new() {
List* list = malloc(sizeof(List));
list->start = NULL;
list->current = NULL;
return list;
}
// Deletes list completely
void list_delete(List* list) {
if(list->start) {
fprintf(stderr, "Attempted list delete before list items were removed\n");
exit(1);
}
free(list);
}