-
Notifications
You must be signed in to change notification settings - Fork 23
/
list.cpp
121 lines (92 loc) · 2.27 KB
/
list.cpp
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
113
114
115
116
117
118
119
120
121
#include "stdafx.h"
#include "spasm.h"
#include "list.h"
#include "utils.h"
/*
* Adds a node to the end of the
* list, returns the new start
* of the list
*/
EXPORT list_t *list_append (list_t *first_node, void *data) {
list_t *curr_node, *new_node;
new_node = (list_t *)malloc (sizeof (list_t));
new_node->data = data;
new_node->next = NULL;
if (first_node == NULL)
return new_node;
curr_node = first_node;
while (curr_node->next)
curr_node = curr_node->next;
curr_node->next = new_node;
return first_node;
}
/*
* Adds a node to the beginning
* of the list, returns the new
* start of the list
*/
EXPORT list_t *list_prepend (list_t *first_node, void *data) {
list_t *new_node;
new_node = (list_t *)malloc (sizeof (list_t));
new_node->data = data;
new_node->next = first_node;
return new_node;
}
/*
* Inserts a node after prev
*/
EXPORT list_t *list_insert(list_t *prev, void *data) {
list_t *new_next;
new_next = (list_t *) malloc(sizeof(list_t));
new_next->data = data;
new_next->next = prev->next;
prev->next = new_next;
return new_next;
}
/*
* Removes a node from the list,
* returns the new start of the
* list
*/
EXPORT list_t *list_remove (list_t *first_node, list_t *remove_node) {
list_t *curr_node;
// if the node to remove is the first one, then it's easy
if (first_node == remove_node)
return first_node->next;
// otherwise, find the node before the node to remove
curr_node = first_node;
while (curr_node->next != remove_node && curr_node != NULL)
curr_node = curr_node->next;
// then move around pointers
if (curr_node != NULL)
curr_node->next = remove_node->next;
return first_node;
}
/*
* Frees a list node
*/
EXPORT void list_free_node (list_t *first_node) {
if (first_node)
free (first_node);
}
/*
* Frees an entire list
*/
EXPORT void list_free (list_t *curr_node, bool free_data, void (*free_callback)(void *)) {
while (curr_node) {
list_t *next = curr_node->next;
if (free_data && curr_node->data)
{
if (free_callback != NULL)
{
free_callback(curr_node->data);
}
else
{
free(curr_node->data);
}
}
list_free_node(curr_node);
curr_node = next;
}
}