10 list
* make_new(list
* next
, void* item
){
14 ptr
= malloc(sizeof(struct list
));
26 void remove_from_list(list
* prev
, list
* node
){
27 prev
->next
= node
->next
;
29 node
->next
= freelist
;
35 return make_new(NULL
, NULL
);
38 void push(list
* L
, void* item
){
39 list
* ptr
= make_new(L
->next
, item
);
45 void* item
= L
->next
->item
;
46 remove_from_list(L
, L
->next
);
54 void append(list
* L
, void* item
){
59 ptr
->next
= make_new(NULL
, item
);
62 void recycle(list
* L
){
65 ptr
->next
->item
= NULL
;
84 static void split(list
* L
, list
** left
, list
** right
){
111 static list
* merge(list
* left
, list
* right
, compare_func cmp
){
112 /* merges right into left */
116 if(left
== NULL
) return right
;
118 if(right
&& cmp(right
->item
, left
->item
) > 0){
126 while(right
&& ptr
->next
){
127 if(cmp(right
->item
, ptr
->next
->item
) > 0){
130 tmp
->next
= ptr
->next
;
139 if(ptr
->next
== NULL
)
145 static list
* merge_sort(list
* L
, compare_func cmp
){
149 if(L
== NULL
) return NULL
;
150 if(L
->next
== NULL
) return L
;
152 split(L
, &left
, &right
);
155 merge_sort(left
, cmp
),
156 merge_sort(right
, cmp
),
161 void sort(list
* L
, compare_func cmp
){
162 L
->next
= merge_sort(L
->next
, cmp
);
167 void print_list(list
* L
, void (*print
)(void* item
)){
179 void println_list(list
* L
, void (*print
)(void* item
)){
180 print_list(L
, print
);
184 void list_print_free(){
185 list
* ptr
= freelist
;
197 void print(void* item
){