Merge branch 'io'
[cantaveria.git] / list.c
blob186968f4c7a4fd6dba3b5cff50aae8c27a6443b8
1 #include <stdlib.h>
2 #include <stdio.h>
5 #include <list.h>
7 list* freelist = NULL;
10 list* make_new(list* next, void* item){
11 list* ptr;
13 if(freelist == NULL){
14 ptr = malloc(sizeof(struct list));
16 else{
17 ptr = freelist;
18 freelist = ptr->next;
21 ptr->next = next;
22 ptr->item = item;
23 return ptr;
26 void remove_from_list(list* prev, list* node){
27 prev->next = node->next;
28 node->item = NULL;
29 node->next = freelist;
30 freelist = node;
34 list* empty(){
35 return make_new(NULL, NULL);
38 void push(list* L, void* item){
39 list* ptr = make_new(L->next, item);
40 L->next = ptr;
43 void* pop(list* L){
44 if(L->next){
45 void* item = L->next->item;
46 remove_from_list(L, L->next);
47 return item;
49 else{
50 return NULL;
55 void append(list* L, void* item){
56 list* ptr = L;
57 while(ptr->next){
58 ptr = ptr->next;
60 ptr->next = make_new(NULL, item);
63 void recycle(list* L){
64 list* ptr = L;
65 while(ptr->next){
66 ptr->next->item = NULL;
67 ptr = ptr->next;
69 ptr->next = freelist;
70 freelist = L;
77 void print_list(list* L, void (*print)(void* item)){
78 list* ptr = L->next;
79 printf("(");
80 while(ptr){
81 print(ptr->item);
82 if(ptr->next)
83 printf(", ");
84 ptr = ptr->next;
86 printf(")");
89 void println_list(list* L, void (*print)(void* item)){
90 print_list(L, print);
91 printf("\n");
94 void list_print_free(){
95 list* ptr = freelist;
96 printf("(");
97 while(ptr){
98 printf("_");
99 if(ptr->next){
100 printf(", ");
102 ptr = ptr->next;
104 printf(")\n");
107 void print(void* item){
108 char* s = item;
109 printf("%s", s);
112 void list_sanitytest(){
113 list* L = empty();
114 char* s;
115 printf("empty: ");
116 println_list(L, print);
118 printf("push a b c: ");
119 push(L, "a");
120 push(L, "b");
121 push(L, "c");
122 println_list(L, print);
124 printf("pop: ");
125 s = pop(L);
126 printf("%s ", s);
127 println_list(L, print);
129 printf("freelist: ");
130 list_print_free();
132 printf("pop: ");
133 s = pop(L);
134 printf("%s ", s);
135 println_list(L, print);
137 printf("freelist: ");
138 list_print_free();
140 printf("append a b c: ");
141 append(L, "a");
142 append(L, "b");
143 append(L, "c");
144 println_list(L, print);
146 printf("freelist: ");
147 list_print_free();
149 printf("recycle: ");
150 recycle(L);
151 list_print_free();