// L-22 MCS 360 Wed 13 Oct 2010 : tower_of_hanoi.cpp

#include <iostream>
#include <stack>
using namespace std;

void write ( stack<int> s );
// writes the contents of the stack s

void write ( stack<int> A, stack<int> B, stack<int> C );
// writes the contents of the three stacks A, B, and C

void hanoi ( int n, stack<int> &A, stack<int> &B, stack<int> &C );
// moves n disks from A to B, using C as auxiliary stack
// to ensure no larger disk every rests on a smaller disk

int main()
{
   cout << "give number of disks : ";
   int n; cin >> n;

   stack<int> A;
   for(int i=0; i<n; i++) A.push(n-i);
   cout << "stack A : "; write(A); cout << endl;

   stack<int> B,C;
   hanoi(n,A,B,C);

   return 0;
}

void write ( stack<int> s )
{
   stack<int> t;

   for(t=s; !t.empty(); t.pop())
      cout << " " << t.top();
}

void write ( stack<int> A, stack<int> B, stack<int> C )
{
   cout << "  A : "; write(A);
   cout << "  B : "; write(B);
   cout << "  C : "; write(C); cout << endl;
}

void hanoi ( int n, stack<int> &A, stack<int> &B, stack<int> &C )
{
   if(n==1)
   {
      B.push(A.top()); A.pop(); // move disk from A to B
      write(A,B,C);
   }
   else 
   {
      hanoi(n-1,A,C,B); // move n-1 disks from A to C, B is auxiliary
      B.push(A.top()); A.pop();  // move nth disk from A to B
      write(A,B,C);
      hanoi(n-1,C,B,A); // move n-1 disks from C to B, A is auxiliary
   }
}

