Animated Hanoi Tower - C++ Data Structure

C++ examples for Data Structure:Stack

Description

Animated Hanoi Tower

Demo Code

#include <iostream>
using namespace std;
#define MAX_LEVELS  10/*from  w ww .  j a  v a  2 s  .co m*/
class Cstack {
   public:
   int rings[MAX_LEVELS];  // Array of ring values.
   int tos;                // Top-of-stack index.
   void populate(int size);  // Initialize stack.
   void clear(int size);     // Clear the stack.
   void push(int n);
   int pop(void);
} stacks[3];
void Cstack::populate(int size) {
   for (int i = 0; i < size; i++) {
      rings[i] = i + 1;
   }
   tos = -1;
}
void Cstack::clear(int size) {
   for (int i = 0; i < size; i++) {
      rings[i] = 0;
   }
   tos = size - 1;
}
void Cstack::push(int n) {
   rings[tos--] = n;
}
int Cstack::pop(void) {
   int n = rings[++tos];
   rings[tos] = 0;
   return n;
}
void move_stacks(int src, int dest, int other, int n);
void move_a_ring(int source, int dest);
void print_stacks(void);
void pr_chars(int ch, int n);
int stack_size = 7;
int main() {
   stacks[0].populate(stack_size);
   stacks[1].clear(stack_size);
   stacks[2].clear(stack_size);
   print_stacks();
   move_stacks(stack_size, 0, 2, 1);
   return 0;
}
void move_stacks(int n, int src, int dest, int other){
   if (n == 1) {
      move_a_ring(src, dest);
   } else {
      move_stacks(n-1, src, other, dest);
      move_a_ring(src, dest);
      move_stacks(n-1, other, dest, src);
   }
}
void move_a_ring(int source, int dest) {
   int n = stacks[source].pop(); // Pop off source.
   stacks[dest].push(n);         // Push onto dest.
   print_stacks();               // Show new state.
}
void print_stacks(void) {
   int n = 0;
   for (int i = 0; i < stack_size; i++) {
      for (int j = 0; j < 3; j++) {
         n = stacks[j].rings[i];
         pr_chars(' ', 12 - n);
         pr_chars('*', 2 * n);
         pr_chars(' ', 12 - n);
      }
      cout << endl;
   }
}
void pr_chars(int ch, int n) {
   for (int i = 0; i < n; i++) {
      cout << (char) ch;
   }
}

Result


Related Tutorials