225. Implement Stack using Queues

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

题意:利用队列实现栈。

方法一:队列为先进先出线性表,栈为先进后出线性表。利用in和out两个队列实现栈。
              入栈时:直接进入in队列即可。
              出栈时:若in队列不空,则应将in队列中队尾元素出队,即将in队列中的除队尾外所有元素出队并按序加入out队列中,再将队尾元素出队;若in队列为空,则应将out队列中队尾元素出队,将out队列中除队尾元素外所有元素出队并按序加入in队列中,将队尾元素出队。

class MyStack {
public:
    queue<int>in,out;
    MyStack() {
        
    }
    void push(int x) {
        in.push(x);
    }
    int pop() {
        int tmp;
        if(!in.empty()){
            while(in.size()>1){
                out.push(in.front());
                in.pop();
            }
            tmp=in.front();
            in.pop();
            return tmp;
        }else {
            while(out.size()>1){
                in.push(out.front());
                out.pop();
            }
            tmp=out.front();
            out.pop();
            return tmp;
        }
    }
    int top() {
        int tmp=pop();
        if(!in.empty())
            in.push(tmp);
        else
            out.push(tmp);
        return tmp;
    }
    bool empty() {
        if(in.empty()&&out.empty())
            return 1;
        else 
            return 0;
    }
};

方法二:使用一个队列实现。在将元素入栈时,将队列中的元素弹出并重新加入队列,并保证新入栈元素处于队首位置。此时栈的出栈,取栈顶元素等操作即为队列的相应操作。

class MyStack {
public:
    queue<int>que;
    MyStack() {

    }
    void push(int x) {
        que.push(x);
        for(int i=0;i<que.size()-1;i++){
            que.push(que.front());
            que.pop();
        }
    }
    int pop() {
       int tmp=que.front();
       que.pop();
       return tmp;
    }
    int top() {
      return que.front();
    }
    bool empty() {
      if(que.empty())
        return 1;
      else
        return 0;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值