Merge branch 'list' into io
[cantaveria.git] / list.c
blobb20d6b95abcd93036dda84ea7f1a7207fe0a077c
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 void* item = L->next->item;
45 remove_from_list(L, L->next);
46 return item;
49 void append(list* L, void* item){
50 list* ptr = L->next;
51 while(ptr->next){
52 ptr = ptr->next;
54 ptr->next = make_new(NULL, item);
57 void recycle(list* L){
58 list* ptr = L;
59 while(ptr->next){
60 ptr->next->item = NULL;
61 ptr = ptr->next;
63 ptr->next = freelist;
64 freelist = L;
71 void print_list(list* L, void (*print)(void* item)){
72 list* ptr = L->next;
73 printf("(");
74 while(ptr){
75 print(ptr->item);
76 if(ptr->next)
77 printf(", ");
78 ptr = ptr->next;
80 printf(")");
83 void println_list(list* L, void (*print)(void* item)){
84 print_list(L, print);
85 printf("\n");
88 void list_print_free(){
89 list* ptr = freelist;
90 printf("(");
91 while(ptr){
92 printf("_");
93 if(ptr->next){
94 printf(", ");
96 ptr = ptr->next;
98 printf(")\n");
101 void print(void* item){
102 char* s = item;
103 printf("%s", s);
106 void list_sanitytest(){
107 list* L = empty();
108 char* s;
109 printf("empty: ");
110 println_list(L, print);
112 printf("push a b c: ");
113 push(L, "a");
114 push(L, "b");
115 push(L, "c");
116 println_list(L, print);
118 printf("pop: ");
119 s = pop(L);
120 printf("%s ", s);
121 println_list(L, print);
123 printf("freelist: ");
124 list_print_free();
126 printf("pop: ");
127 s = pop(L);
128 printf("%s ", s);
129 println_list(L, print);
131 printf("freelist: ");
132 list_print_free();
134 printf("append a b c: ");
135 append(L, "a");
136 append(L, "b");
137 append(L, "c");
138 println_list(L, print);
140 printf("freelist: ");
141 list_print_free();
143 printf("recycle: ");
144 recycle(L);
145 list_print_free();