C++ 用两个栈实现一个队列

本文介绍了一种使用栈实现队列的方法。通过两个栈的相互转换来完成队列的尾部添加和头部删除操作。首先将一个栈的所有元素转移到另一个栈,然后在第一个栈中添加新元素,再将第二个栈的元素转回第一个栈,以此实现队列的先进先出特性。

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

#include<iostream>
using namespace std;
class stack;
class stack_node
{
    friend class stack;
public:
    stack_node(int val, stack_node *p):value(val),next(p)
    {}
    ~stack_node()
    {}
private:
    int value;
    stack_node *next;
};

class stack
{
public:
    stack()
    {
        stack_node *s = buynode(0,NULL);
        sta = dir = s;
    }
    ~stack()
    {
        while(!empty())
        {
            stack_node *d = dir;
            dir = dir->next;
            delete d;
        }
        delete sta;
    }
    stack_node* buynode(int val, stack_node *p)
    {
        stack_node *tmp = new stack_node(val, p);
        if (tmp != 0)
        {
            return tmp;
        }
        return 0;
    }

    void push(int val)
    {
        stack_node *s = buynode(val, dir);
        dir = s;
    }
    int pop()
    {
        if(!empty())
        {
            int tmp = dir->value;
            dir = dir->next;
            return tmp;
        }
        return -1;
    }
    bool empty()
    {
        if(dir->next != NULL)
        {
            return false;
        }
        return true;
    }
private:
    stack_node *sta;
    stack_node *dir;
};

class queue
{
public:
    queue()
    {
        sta1 = new stack();
        sta2 = new stack();
    }
    ~queue()
    {
        delete sta1;
        delete sta2;
    }
    void appendtail(int val)
    {
        while(!sta1->empty())
        {
            sta2->push(sta1->pop());
        }
        sta1->push(val);
        while(!sta2->empty())
        {
            sta1->push(sta2->pop());
        }
    }
    int deletehead()
    {
        if(!sta1->empty())
        {
            return sta1->pop();
        }
        return -1;
    }
private:
    stack *sta1;
    stack *sta2;
};
int main()
{
    queue que;
    for(int i=0; i<5; i++)
    {
        que.appendtail(i);
    }
    for(int i=0; i<5; i++)
    {
        cout<<que.deletehead()<<endl;
    }
//  stack sta;
//  for(int i=0; i<5; i++)
//  {
//      sta.push(i);
//  }
//  for(int i=0; i<7; i++)
//  {
//      cout<<sta.pop()<<endl;
//  }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值