// incomplete and very simple version #include class Stack { char stackName; int top; int s[100]; public: Stack(char name) { stackName = name; top = -1; for(int i = 0; i < 100; i++) { s[i] = 0; } } void push(int x) { top++; s[top] = x; } int pop() { int x = s[top]; s[top] = 0; top--; return x; } void display() { printf("%c: ",stackName); int x, i = 0; while((x = s[i]) > 0) { printf("%d",x); i++; } printf("\n"); } char getName() { return stackName; } int getAt(int i) { return s[i]; } }; class Console { char **s; int nDisc; public: Console(int n) { int i; nDisc = n; // dynamic allocation for 2 dimension array s = new char*[nDisc+1]; for(i = 0; i < nDisc+1; i++) { s[i] = new char[3*(nDisc+3)]; } resetScreen(); } void resetScreen() { int i,j; for(i = 0; i < nDisc+1; i++) { for(j = 0; j < 3*(nDisc+3); j++) { s[i][j] = ' '; if (i == nDisc) { if (j%(nDisc+3) != 0) s[i][j] = '='; } } } s[nDisc][2] = 'A'; s[nDisc][nDisc+5] = 'B'; s[nDisc][2*nDisc+8] = 'C'; } void drawDisc(char name, Stack *tower) { int x; int i,j; int pos = name - 'A' + 1; // 'A' -> 1, 'B' -> 2, 'C' -> 3 int startPos = (pos-1)*(nDisc+3)+2; i = 0; while((x = tower->getAt(i)) != 0) { i++; for(j = startPos; j < startPos+x; j++) { s[nDisc-i][j] = '*'; } } } void show() { int i,j; for(i = 0; i < nDisc+1; i++) { for(j = 0; j < 3*(nDisc+3); j++) { printf("%c",s[i][j]); } printf("\n"); } } }; void printStack(char name,Stack *x,Stack *y,Stack *z,Console *screen) { if (x->getName() == name) screen->drawDisc(name,x); if (y->getName() == name) screen->drawDisc(name,y); if (z->getName() == name) screen->drawDisc(name,z); } void moveHanoi(int n,Stack *from,Stack *temp,Stack *to,Console *screen) { if (n == 1) { int x = from->pop(); to->push(x); screen->resetScreen(); printStack('A',from,temp,to,screen); printStack('B',from,temp,to,screen); printStack('C',from,temp,to,screen); screen->show(); return; } moveHanoi(n-1,from,to,temp,screen); moveHanoi(1,from,temp,to,screen); moveHanoi(n-1,temp,from,to,screen); } void main() { Stack a('A'); Stack b('B'); Stack c('C'); Console screen(5); a.push(5); a.push(4); a.push(3); a.push(2); a.push(1); screen.drawDisc('A',&a); screen.show(); moveHanoi(5,&a,&b,&c,&screen); }