-
Notifications
You must be signed in to change notification settings - Fork 65
/
llist.c
90 lines (76 loc) · 2.19 KB
/
llist.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
#include "include/llist.h"
void add_node(bin_t *bin, node_t* node) {
node->next = NULL;
node->prev = NULL;
node_t *temp = bin->head;
if (bin->head == NULL) {
bin->head = node;
return;
}
// we need to save next and prev while we iterate
node_t *current = bin->head;
node_t *previous = NULL;
// iterate until we get the the end of the list or we find a
// node whose size is
while (current != NULL && current->size <= node->size) {
previous = current;
current = current->next;
}
if (current == NULL) { // we reached the end of the list
previous->next = node;
node->prev = previous;
}
else {
if (previous != NULL) { // middle of list, connect all links!
node->next = current;
previous->next = node;
node->prev = previous;
current->prev = node;
}
else { // head is the only element
node->next = bin->head;
bin->head->prev = node;
bin->head = node;
}
}
}
void remove_node(bin_t * bin, node_t *node) {
if (bin->head == NULL) return;
if (bin->head == node) {
bin->head = bin->head->next;
return;
}
node_t *temp = bin->head->next;
while (temp != NULL) {
if (temp == node) { // found the node
if (temp->next == NULL) { // last item
temp->prev->next = NULL;
}
else { // middle item
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
}
// we dont worry about deleting the head here because we already checked that
return;
}
temp = temp->next;
}
}
node_t *get_best_fit(bin_t *bin, size_t size) {
if (bin->head == NULL) return NULL; // empty list!
node_t *temp = bin->head;
while (temp != NULL) {
if (temp->size >= size) {
return temp; // found a fit!
}
temp = temp->next;
}
return NULL; // no fit!
}
node_t *get_last_node(bin_t *bin) {
node_t *temp = bin->head;
while (temp->next != NULL) {
temp = temp->next;
}
return temp;
}