-
Notifications
You must be signed in to change notification settings - Fork 0
/
singly_linked_list.c
127 lines (110 loc) · 2.4 KB
/
singly_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
#include <stdlib.h>
#include <stdio.h>
#include "singly_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);
bool finished = FALSE;
while(!finished){
finished = TRUE;
while(current->next){
if (filter(current->data, current->next->data)) {
swap(¤t, ¤t->next);
finished = FALSE;
}
current = current->next;
}
current = (*head_ref);
}
}
void push(LIST_NODE **head_ref, void *element){
LIST_NODE *node = (LIST_NODE *) malloc(sizeof(LIST_NODE));
node->data = element;
node->next = *head_ref;
*head_ref = node;
}
void append(LIST_NODE **head_ref, void *element){
LIST_NODE *node = (LIST_NODE *) malloc(sizeof(LIST_NODE));
LIST_NODE *tail = last_node(*head_ref);
node->data = element;
node->next = NULL;
if (!*head_ref) {
*head_ref = node;
}
else{
tail->next = node;
}
}
void for_each(LIST_NODE *head, iterator iterator){
LIST_NODE *node = head;
while(node){
iterator(node->data);
node = node->next;
}
}
void for_each_reverse(LIST_NODE *head, iterator iterator){
LIST_NODE *node = head;
if(node){
for_each_reverse(node->next, iterator);
iterator(node->data);
}
}
LIST_NODE * last_node(LIST_NODE *head){
LIST_NODE *node = head;
if (node) {
while(node->next){
node = node->next;
}
}
return node;
}
void destroy(LIST_NODE **head_ref){
LIST_NODE *current = *head_ref;
LIST_NODE *next;
while(current){
next = current->next;
free(current->data);
free(current);
current = next;
}
*head_ref = NULL;
}
void remove_all(LIST_NODE **head_ref, filter filter, void * filter_arg ){
LIST_NODE *aux = *head_ref;
LIST_NODE *next;
LIST_NODE *prev = NULL;
while(aux){
next = aux->next;
if (filter(aux->data, filter_arg)) {//remove
if (aux == *head_ref) {//first element
*head_ref = aux->next;
}
else {
prev->next = aux->next;
}
free(aux->data);
free(aux);
aux = NULL;
}
if (aux) {
prev = aux;
}
aux = next;
}
}
int list_size(LIST_NODE *head){
unsigned int i = 0;
LIST_NODE *node = head;
while(node){
i++;
node = node->next;
}
return i;
}