-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.c
More file actions
74 lines (65 loc) · 1.9 KB
/
list.c
File metadata and controls
74 lines (65 loc) · 1.9 KB
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
#include <stdio.h>
#include <stdlib.h>
struct list_t {
int value;
struct list_t * node;
};
struct list_meta {
int counter;
int index;
};
static struct list_t * prepend(struct list_t * list, int value) {
struct list_t * next = malloc(sizeof(struct list_t));
next->value = value;
next->node = list;
return next;
}
static struct list_t * remfirst(struct list_t * list) {
struct list_t * prev = list->node;
free(list);
return prev;
}
static int cb_printer(int value, void * userdata) { /* Callback printer - just prints each list element's value */
printf("%d\n", value);
return 0;
}
static int cb_indexer(int value, void * userdata) { /* Callback indexer - prints each list element's value and 'index' */
struct list_meta * metadata = userdata;
metadata->counter++;
printf("Value %d has index %d\n", value, metadata->counter);
return 0;
}
static int cb_finder(int value, void * userdata) { /* Callback finder - finds an element by specified index */
struct list_meta * metadata = userdata;
metadata->counter++;
if (metadata->counter == metadata->index) {
printf("Found %d by %d index\n", value, metadata->index);
}
return 0;
}
static void traverse(struct list_t * list, int (*callback)(int, void *), void * userdata) {
if (list != NULL) {
int result = callback(list->value, userdata);
if (result) {
return;
}
traverse(list->node, callback, userdata);
}
return;
}
int main() {
struct list_t * list = NULL;
struct list_meta metadata; /* Metadata for: 1. Search by index; 2. Count the length */
list = prepend(list, 10);
list = prepend(list, 11);
list = prepend(list, 12);
list = prepend(list, 13);
list = remfirst(list);
metadata.counter = 0;
metadata.index = 2;
/* traverse(list, cb_printer, NULL); prints only a value of the each list element - replaced with cb_indexer */
traverse(list, cb_indexer, &metadata);
metadata.counter = 0;
traverse(list, cb_finder, &metadata);
return 0;
}