用栈解决汉诺塔问题

版权声明:小简原创 https://blog.csdn.net/qq_43469554/article/details/87876167
#include <iostream>
#include <stack>
using namespace std;
stack<int> S[3];
void move (int x, int y)
{
    int temp = S[x].top();
    S[x].pop();
    S[y].push(temp);
    cout << x << "-->" << y << endl;
}
void hanoi(int A, int B, int C, int n)
{
    if (n == 1)
    {
        move(A, C);
        return;
    }
    hanoi(A, C, B, n - 1);
    move(A, C);
    hanoi(B, A, C, n - 1);
}
int main() 
{
    int n;
    cin >> n;
    for (int i = n; i >= 1; i--)
    {
        S[0].push(i);
	}
    hanoi(0, 1, 2, n);
    while (!S[2].empty())
    {
        cout << S[2].top() << " ";
        S[2].pop();
    }
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43469554/article/details/87876167