用队列实现栈

leetcode-225.    用队列实现栈

使用队列实现栈的下列操作:

1.push(x) -- 元素 x 入栈 

 void push(int x) {
       q.push(x);
    }
//压栈是一样的就不用修改了

2.pop() -- 移除栈顶元素

      栈的栈顶是最后一个元素,按照栈的规则是FILO(先进后出),而栈的栈顶对于队列来说就是最后一个要出来的。

要移除栈顶元素就要先将队列前面的值全部移走再进去,就完成了POP的操作

int pop() {
        int size = q.size()-1;
        for(int i=0;i<size;i++)
        {
            int data = q.front();        //取出口第一个数保存
            q.pop();                    //取出这个数
            q.push(data);                //将取出的数放到队列的最后
        }
        int d = q.front();        //当把所有前面的值都移走了之后,再把第一个元素移除
        q.pop();
        return d;
        
    }

3.top() -- 获取栈顶元素

int top() {
         int size = q.size()-1;
        for(int i=0;i<size;i++)
        {
            int data = q.front();
            q.pop();
            q.push(data);
        }
            //和上一步是一样的,不过这次是将栈顶元素也保存下来送回队列里
        int d = q.front();
        q.pop();
        q.push(d); //只是观看栈顶元素,并不需要移除
        return d; //返回栈顶元素
    }

4.empty() -- 返回栈是否为空

 bool empty() {
        if(!q.empty()){
            return false;
        }
        else
        {
            return true;
        }
    }

完整代码:

class MyStack {
public:
    /** Initialize your data structure here. */
    queue<int> q;
    MyStack() {
    }
    
    /** Push element x onto stack. */
    void push(int x) {
       q.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = q.size()-1;
        for(int i=0;i<size;i++)
        {
            int data = q.front();
            q.pop();
            q.push(data);
        }
        int d = q.front();
        q.pop();
        return d;
        
    }
    
    /** Get the top element. */
    int top() {
         int size = q.size()-1;
        for(int i=0;i<size;i++)
        {
            int data = q.front();
            q.pop();
            q.push(data);
        }
              
        int d = q.front();
        q.pop();
        q.push(d); 
        return d; 
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        if(!q.empty()){
            return false;
        }
        else
        {
            return true;
        }
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * bool param_4 = obj.empty();
 */

 

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值