sailing

Everything...

c++解决汉诺塔,显示每一步的碟子情况 C++ hanoi with trace of every step

 

 

#include "stdafx.h"

#include <iostream>

#include <stack>

 

void StartHanoi(int n);

void Hanoi(int length, std::stack<int>* source, std::stack<int>* middle, std::stack<int>* destination);

void PrintStack();

void PrintAStack(std::stack<int> stackToBePrint);

 

std::stack <int> source, middle, destination;

 

int _tmain(int argc, _TCHAR* argv[])

{

    int iNumDisc = 0;

    while(iNumDisc<=0)

    {

       std::cin>>iNumDisc;

    }

    StartHanoi(iNumDisc);

    return 0;

}

 

void StartHanoi(int n)

{  

    if(n<=0)

    {

       return;

    }

    for(int i=n;i>0;i--)

    {

       source.push(i);

    }

    PrintStack();

    Hanoi(source.size(),&source,&middle,&destination);

}

 

void Hanoi(int length, std::stack<int>* psource, std::stack<int>* pmiddle, std::stack<int>* pdestination)

{

    if(length==0)

    {

       return;

    }

    //  Move n-1 to middle

    if(length>1)

    {

       Hanoi(length-1, psource, pdestination, pmiddle);

    }

    // Move last disc in the source pole to destination pole

    int temp = psource->top();

    psource->pop();

    pdestination->push(temp);

    PrintStack();

    //  Move middle to destination

    if(length>1)

    {

       Hanoi(length-1, pmiddle, psource, pdestination);

    }

}

 

void PrintStack()

{

    PrintAStack(source);

    PrintAStack(middle);

    PrintAStack(destination);

    std::cout<<std::endl;

}

 

void PrintAStack(std::stack<int> stackToBePrint)

{

    if(stackToBePrint.size()<=0)

    {

       std::cout<<'-'<<std::endl;

       return;

    }

    //  source

    while(stackToBePrint.size()>0)

    {

       int temp = stackToBePrint.top();

       stackToBePrint.pop();

       std::cout<<temp<<' ';

    }

    std::cout<<std::endl;

}

posted on 2007-01-28 18:47  乌生鱼汤  阅读(567)  评论(0编辑  收藏  举报

导航