Added music.c module.
[cantaveria.git] / list.c
blobbe3f40fb8852699049533c57f44306cf7fedfb45
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;
54 void append(list* L, void* item){
55 list* ptr = L;
56 while(ptr->next){
57 ptr = ptr->next;
59 ptr->next = make_new(NULL, item);
62 void recycle(list* L){
63 list* ptr = L;
64 while(ptr->next){
65 ptr->next->item = NULL;
66 ptr = ptr->next;
68 ptr->next = freelist;
69 freelist = L;
76 void print_list(list* L, void (*print)(void* item)){
77 list* ptr = L->next;
78 printf("(");
79 while(ptr){
80 print(ptr->item);
81 if(ptr->next)
82 printf(", ");
83 ptr = ptr->next;
85 printf(")");
88 void println_list(list* L, void (*print)(void* item)){
89 print_list(L, print);
90 printf("\n");
93 void list_print_free(){
94 list* ptr = freelist;
95 printf("(");
96 while(ptr){
97 printf("_");
98 if(ptr->next){
99 printf(", ");
101 ptr = ptr->next;
103 printf(")\n");
106 void print(void* item){
107 char* s = item;
108 printf("%s", s);
111 void list_sanitytest(){
112 list* L = empty();
113 char* s;
114 printf("empty: ");
115 println_list(L, print);
117 printf("push a b c: ");
118 push(L, "a");
119 push(L, "b");
120 push(L, "c");
121 println_list(L, print);
123 printf("pop: ");
124 s = pop(L);
125 printf("%s ", s);
126 println_list(L, print);
128 printf("freelist: ");
129 list_print_free();
131 printf("pop: ");
132 s = pop(L);
133 printf("%s ", s);
134 println_list(L, print);
136 printf("freelist: ");
137 list_print_free();
139 printf("append a b c: ");
140 append(L, "a");
141 append(L, "b");
142 append(L, "c");
143 println_list(L, print);
145 printf("freelist: ");
146 list_print_free();
148 printf("recycle: ");
149 recycle(L);
150 list_print_free();