-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_linked_list.c
134 lines (118 loc) · 2.56 KB
/
doubly_linked_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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <stdlib.h>
#include <stdio.h>
#include "doubly_linked_list.h"
LIST_NODE * initialize(void){
return NULL;
}
void swap(LIST_NODE **node1, LIST_NODE **node2){
void *data = (*node2)->data;
(*node2)->data = (*node1)->data;
(*node1)->data = data;
}
void sort(LIST_NODE **head_ref, filter filter){
LIST_NODE *current = (*head_ref)->next;
bool finished = FALSE;
while(!finished){
finished = TRUE;
while(current){
if (filter(current->data, current->prev->data)) {
swap(¤t, ¤t->prev);
finished = FALSE;
}
current = current->next;
}
current = (*head_ref)->next;
}
}
void push(LIST_NODE **head_ref, void *element){
LIST_NODE *node = (LIST_NODE *) malloc(sizeof(LIST_NODE));
node->data = element;
node->prev = NULL;
node->next = *head_ref;
if (*head_ref) {
node->next->prev = node;
}
*head_ref = node;
}
void append(LIST_NODE **head_ref, void *element){
LIST_NODE *node = (LIST_NODE *) malloc(sizeof(LIST_NODE));
LIST_NODE *aux = *head_ref;
node->data = element;
node->next = NULL;
if (!aux) {//empty list
node->prev = NULL;
*head_ref = node;
}
else{
aux = last_node(*head_ref);
aux->next = node;
node->prev = aux;
}
}
void for_each(LIST_NODE *head, iterator iterator){
LIST_NODE *node = head;
while(node){
iterator(node->data);
node = node->next;
}
}
LIST_NODE * last_node(LIST_NODE *head){
LIST_NODE *node = head;
if (node) {
while(node->next){
node = node->next;
}
}
return node;
}
void for_each_reverse(LIST_NODE *head, iterator iterator){
LIST_NODE *node = head;
node = last_node(head);
while(node){
iterator(node->data);
node = node->prev;
}
}
void destroy(LIST_NODE **head_ref){
LIST_NODE *aux = *head_ref;
while(*head_ref){
aux = *head_ref;
*head_ref = aux->next;
free(aux->data);
free(aux);
aux = NULL;
}
free(*head_ref);
*head_ref = NULL;
}
void remove_all(LIST_NODE **head_ref, filter filter, void * filter_arg ){
LIST_NODE *aux = *head_ref;
LIST_NODE *next;
while(aux){
next = aux->next;
if (filter(aux->data, filter_arg)) {//remove
if (!aux->prev) {//first element
*head_ref = aux->next;
}
else {
aux->prev->next = aux->next;
}
if (aux->next) {
aux->next->prev = aux->prev;
}
free(aux->data);
free(aux);
aux = NULL;
}
aux = next;
}
}
int list_size(LIST_NODE *head){
unsigned int i = 0;
LIST_NODE *node = head;
while(node){
i++;
node = node->next;
}
return i;
}