#include #include "towers.h" make_move(Dllist *towers, int from, int to) { int piece, topofto; /* Error check -- is the first tower empty? */ if (dll_empty(towers[from])) { printf("Illegal move of tower %d to %d\n", from, to); return; } piece = jval_i(dll_val(dll_first(towers[from]))); /* Error check -- is the piece too big to go on the destination tower? */ if (!dll_empty(towers[to])) { topofto = jval_i(dll_val(dll_first(towers[to]))); if (piece > topofto) { printf("Illegal move of tower %d to %d\n", from, to); return; } } /* Move the piece from the first tower to the second */ dll_delete_node(dll_first(towers[from])); dll_prepend(towers[to], new_jval_i(piece)); /* Print that the piece has moved */ printf("Moved piece %3d from tower %d to tower %d\n", piece, from, to); } /* Print the towers by traversing the list backwards */ print_towers(Dllist *towers) { int i; Dllist tmp; for (i = 0; i < 3; i++) { printf("Tower %d:", i); dll_rtraverse(tmp, towers[i]) { printf("%3d", jval_i(dll_val(tmp))); } printf("\n"); } } /* Allocate the towers and put npiece disks on tower 0 */ Dllist *new_towers(int npiece) { Dllist *t; int i; int piece; t = (Dllist *) malloc(sizeof(Dllist)*3); for (i = 0; i < 3; i++) { t[i] = new_dllist(); } for (piece = 1; piece <= npiece; piece++) { dll_append(t[0], new_jval_i(piece)); } return t; }