Added list length function.
[cantaveria.git] / list.c
blob3818adb1adaa002bfd9f4f40cd2b52b2acbda774
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;
73 int length(list* L){
74 list* ptr = L->next;
75 int c = 0;
76 while(ptr){
77 c += 1;
78 ptr = ptr->next;
80 return c;
86 void print_list(list* L, void (*print)(void* item)){
87 list* ptr = L->next;
88 printf("(");
89 while(ptr){
90 print(ptr->item);
91 if(ptr->next)
92 printf(", ");
93 ptr = ptr->next;
95 printf(")");
98 void println_list(list* L, void (*print)(void* item)){
99 print_list(L, print);
100 printf("\n");
103 void list_print_free(){
104 list* ptr = freelist;
105 printf("(");
106 while(ptr){
107 printf("_");
108 if(ptr->next){
109 printf(", ");
111 ptr = ptr->next;
113 printf(")\n");
116 void print(void* item){
117 char* s = item;
118 printf("%s", s);