程序员面试题精选(48):两个堆栈模拟队列c++代码实现

代码如下:

#include <iostream>

using namespace std;

class ZStackQueue
{
public:
    class ZStack
    {
    public:
        ZStack(int size);
        ~ZStack();
  
        int Pop();
        void Push(int e);
        bool Empty(){return top == 0;}
  
    private:
        int *s;
        int top;
        int size;
    };
 
 public:
  ZStackQueue(int n) : s1(n), s2(n){}
  void EnQueue(int e);
  int DeQueue();
  
 private:
  ZStack s1, s2;
};

ZStackQueue::ZStack::ZStack(int n)
: s(0), top(0), size(n)
{
    s = new int[size]();
}

ZStackQueue::ZStack::~ZStack()
{
    if (s)
    {
        delete [] s;
        s = 0;
    }
 
    top = 0;
    size = 0;
}

int ZStackQueue::ZStack::Pop()
{
    if (top > 0)
        return s[--top];
    else
        return ~0;
}

void ZStackQueue::ZStack::Push(int e)
{
    if (top < size)
        s[top++] = e;
}

void ZStackQueue::EnQueue(int e)
{
    s1.Push(e);
}

int ZStackQueue::DeQueue()
{
    if (!s2.Empty())
    {
        return s2.Pop();
    }
    else
    {
        while (!s1.Empty())
            s2.Push(s1.Pop());
  
        return s2.Pop();
    }
}
int main()
{
 ZStackQueue q(3);
 q.EnQueue(5);
 q.EnQueue(2);
 q.EnQueue(8);
 cout<<q.DeQueue()<<"/t";//<<q.DeQueue()<<"/t"<<q.DeQueue()<<endl;     //如果这样写的话,输出的结果会让你误以为这不是个栈吗,哪是队列呀!呵呵,原因大侠一看都知道的!
 cout<<q.DeQueue()<<"/t";
 cout<<q.DeQueue()<<"/t";
 return 0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值