C++用队列实现栈以及队列实现栈

一、用一个队列实现栈

思路:

  • push:先把元素放到栈中,然后将元素中的size-1个元素插入到队列的尾部。
  • top:由于push操作已经将队列中的元素操作成了先进后出的类型,因此可以直接front取出元素。

代码实现:

class MyStack {

  queue<int> qu;

public:

  /** Initialize your data structure here. */

  MyStack() {



  }

  

  /** Push element x onto stack. */

  void push(int x) {

​    qu.push(x);

​    for(int i=0;i<qu.size()-1;i++)

​    {

​      qu.push(qu.front());

​      qu.pop();

​    }

  }

  

  /** Removes the element on top of the stack and returns that element. */

  int pop() {

​    int val=qu.front();

​    qu.pop();

​    return val;

  }

  

  /** Get the top element. */

  int top() {

​    return qu.front();

  }

  

  /** Returns whether the stack is empty. */

  bool empty() {

​    return qu.empty();

  }

};

二、用两个栈实现队列

思路:

  • push:直接将元素放入到第一个栈中。
  • pop:如果第二个栈中的元素为空,那么将第一个栈中的所有元素放到第二个栈中,然后返回第二个栈的栈顶元素。如果第二个栈中的元素不为空,那么直接返回栈顶元素。

三、用两个队列实现栈

思路:

  • push:直接将元素放到第一个队列中。
  • pop:将队列1中的元素放到队列2中,直到到最后一个元素时,直接把最后一个元素返回就是栈中的第一个元素。

代码实现:

class MyStack { 
queue<int> pushqu;

  queue<int> popqu;

  int topvalue;

public:

  /** Initialize your data structure here. */

  MyStack() {



  }

  

  /** Push element x onto stack. */

  void push(int x) {

​    pushqu.push(x);

​    topvalue=x;

  }

  

  /** Removes the element on top of the stack and returns that element. */

  int pop() {

​    while(pushqu.size()>1)

​    {

​      topvalue=pushqu.front();

​      popqu.push(topvalue);

​      pushqu.pop();

​    }

​    int result=pushqu.front();

​    pushqu.pop();

​    queue<int> temp=pushqu;

​    pushqu=popqu;

​    popqu=temp;

​    return result;

  }

  

  /** Get the top element. */

  int top() {

​    return topvalue;

  }

  

  /** Returns whether the stack is empty. */

  bool empty() {

​    return pushqu.empty();

  }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值