-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.c
90 lines (76 loc) · 1.52 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
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
struct ListEntry *
listAppend(List *list, void *data)
{
if (list == NULL) {
fprintf(stderr, "Bad list pointer?! %p\n", list);
return NULL;
}
ListEntry *entry = NULL;
if ((entry = malloc(sizeof(*entry))) == NULL) {
fprintf(stderr, "Can't allocate new list entry: %s\n", strerror(errno));
return NULL;
}
entry->data = data;
entry->prev = list->tail;
entry->next = NULL;
if (list->tail != NULL) {
list->tail->next = entry;
} else {
list->head = entry;
}
list->tail = entry;
list->len++;
return entry;
}
/*
* NULL Error occurred.
* non-NULL Returns the data from the entry that was removed.
*/
void *
listRemove(List *list, ListEntry *entry)
{
if (list == NULL) {
fprintf(stderr, "Bad list pointer?! %p\n", list);
return NULL;
}
if (entry->prev == NULL) {
list->head = entry->next;
} else {
entry->prev->next = entry->next;
}
if (entry->next == NULL) {
list->tail = entry->prev;
} else {
entry->next->prev = entry->prev;
}
list->len--;
void *data = entry->data;
free(entry);
return data;
}
void *
listNext(List *list, ListEntry **entry)
{
if (list == NULL) {
fprintf(stderr, "Bad list pointer?! %p\n", list);
return (void *)-1;
}
if (entry == NULL) {
fprintf(stderr, "Bad entry pointer?! %p\n", entry);
return (void *)-1;
}
if (*entry == NULL) {
*entry = list->head;
} else {
*entry = (*entry)->next;
}
if (*entry != NULL) {
return (*entry)->data;
}
return NULL;
}