/* Integer linked lists by Mark A. Sheldon, February 2005 */ #include #include #include typedef int DATA; void print_datum(DATA d) { printf("%d", d); } /* Need an abstraction for reading, too. */ struct node { DATA car; /* Data */ struct node *cdr; /* Next */ }; typedef struct node *List; #define NIL NULL List cons(DATA car, List cdr) { List new_node; if ( (new_node = (List) malloc(sizeof(struct node))) == NULL ) { perror("cons"); exit(errno); } new_node->cdr = cdr; new_node->car = car; return new_node; } DATA car(List l) { return l->car; } List cdr(List l) { return l->cdr; } int nullp(List l) { return l == NIL; } static List reverse_iter(List l, List accumulator) { if (nullp(l)) return accumulator; else return reverse_iter(cdr(l), cons(car(l), accumulator)); } List reverse(List l) { return reverse_iter(l, NIL); } void print_list(List l) { List ltmp; for (ltmp = l; !nullp(ltmp); ltmp = cdr(ltmp)) printf("%d -> ", car(ltmp)); printf("NIL\n"); } void destroy_list(List l) { if (nullp(l)) return; destroy_list(cdr(l)); free(l); } int main() { List l = NIL, another_l; DATA n; /* Wouldn't this be nicer? while (!feof(stdin)) l = cons(read_datum(), l); */ while (!feof(stdin)) { if (scanf("%d", &n) != 1) continue; l = cons(n, l); } print_list(l); another_l = reverse(l); print_list(another_l); destroy_list(another_l); print_list(another_l); } /* main () */