blob: 0eeb19b33940462fae2315f0df3db0b0e5b0d0d7 (
plain)
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
|
#include <stdlib.h>
#include "linked_list.h"
linked_list *get_head(linked_list *node) {
linked_list *head;
for (head = node; head != NULL && head->prev != NULL; head = head->prev);
return head;
}
linked_list *get_tail(linked_list *node) {
linked_list *tail;
for (tail = node; tail != NULL && tail->next != NULL; tail = tail->next);
return tail;
}
linked_list *add_node(linked_list **tail, void *data) {
if (tail == NULL) {
return NULL;
} else {
linked_list *node = calloc(1, sizeof(linked_list));
if (node == NULL) {
return NULL;
} else {
node->next = NULL;
node->data = data;
if (*tail == NULL) {
node->prev = NULL;
*tail = node;
} else {
(*tail)->next = node;
node->prev = *tail;
}
return node;
}
}
}
void remove_node(linked_list *node) {
if (node != NULL) {
if (node->prev != NULL) {
node->prev->next = node->next;
}
if (node->next != NULL) {
node->next->prev = node->prev;
}
free(node);
}
}
void cleanup_linked_list(linked_list *node) {
if (node != NULL) {
for (node = get_tail(node); node != NULL; node = node->prev) {
if (node->next != NULL) {
remove_node(node->next);
}
}
remove_node(node);
}
}
void **linked_list_to_array(linked_list *node) {
void **arr = calloc(linked_list_size(get_tail(node))+1, sizeof(void *));
int i = 0;
for (linked_list *n = get_head(node); n != NULL; n = n->next, ++i) {
arr[i] = n->data;
}
arr[i] = NULL;
return arr;
}
int linked_list_size(linked_list *tail) {
int i = 0;
for (linked_list *node = tail; node != NULL; node = node->prev, ++i);
return i;
}
|