crack the code interview 3.4

本文介绍了一个使用栈数据结构解决汉诺塔问题的C++程序实例。通过定义Stack类来实现基本的栈操作,并创建Hanoi类来演示如何移动不同大小的圆盘以解决汉诺塔问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std;

struct StackNode{
    int value;
    StackNode * next;
    StackNode(int v)
    {
        value = v;
        next = NULL; 
    }
};

class Stack
{
private:
    StackNode * head;
public:
    Stack()
    {
        head = NULL;
    }
    ~Stack()
    {
        while (head != NULL)
        {
            StackNode * node = head;
            head = head->next;
            delete node;
        }
        head = NULL;
    }
    void push(int value)
    {
        StackNode * node = new StackNode(value);
        if (head == NULL)
            head = node;
        else
        {
            node->next = head;
            head = node;
        }
    }
    int pop()
    {
        if (head == NULL)
        {
            cout<<"error"<<endl;
            return -1;
        }
        StackNode * node = head;
        int value = node->value;
        head = head->next;
        delete node;
        return value;
    }
    int top()
    {
        if (head != NULL)
            return head->value;
        else
        {
            cout<<"NULL"<<endl;
            return -1;
        }
    }
    bool isEmpty()
    {
        return head == NULL;
    }
};


class Hanoi
{
private:
    Stack stick[3];
    int num;
public:
    Hanoi(int n)
    {
        num = n;
        for (int i = n; i > 0; i--)
        {
            stick[0].push(i);
        }
    }
    void move(int x, int y, int z, int n)
    {
        if (n == 1)
        {
            int value = stick[x].pop();
            stick[z].push(value);
            cout<<"move from "<<x<<" to "<<z<<endl;
        }
        else if (n == 2)
        {
            int value = stick[x].pop();
            stick[y].push(value);
            cout<<"move from "<<x<<" to "<<y<<endl;
            value = stick[x].pop();
            stick[z].push(value);
            cout<<"move from "<<x<<" to "<<z<<endl;
            value = stick[y].pop();
            stick[z].push(value);
            cout<<"move from "<<y<<" to "<<z<<endl;
        }
        else
        {
            move(x, z, y, n - 1);
            move(x, y, z, 1);
            move(y, z, x, n - 1);
        }
    }
};

int main()
{
    Hanoi h(3);
    h.move(0,1,2,3);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值