Leetcode232栈实现队列

/*************************************************************************
	> File Name: Leetcode232.cpp
	> Author: Zcy
	> Mail: 296763002@qq.com
	> Created Time: 四  4/18 18:54:37 2019
 ************************************************************************/

//栈实现队列
//方法一:两个队列,一个队列用于存,另一个队列用于反转(删除头,返回头操作),之后再反转回去
//方法二:把队列反转,需要用一个临时队列

//方法一代码:
class MyQueue {
private:
    stack<int> p, q;
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        p.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        while(!p.empty()) {
            q.push(p.top());
            p.pop();
        }
        
        int k = q.top();
        q.pop();
        
        while(!q.empty()) {
            p.push(q.top());
            q.pop();
        }
        
        return k;
    }
    
    /** Get the front element. */
    int peek() {
        while(!p.empty()) {
            q.push(p.top());
            p.pop();
        }
        
        int k = q.top();
        
        while(!q.empty()) {
            p.push(q.top());
            q.pop();
        }
        
        return k;
    
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return p.empty();   
    }
};



//方法二:
class MyQueue {
private:
    stack<int> p, q;
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        while(!p.empty()) {
            q.push(p.top());
            p.pop();
        }
        
        q.push(x);
        
        while(!q.empty()) {
            p.push(q.top());
            q.pop();
        }
        
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int k = peek();
        p.pop();
        
        return k;
    }
    
    /** Get the front element. */
    int peek() {
        return p.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return p.empty();   
    }
};


/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

转载请注明出处!!!

如果有写的不对或者不全面的地方 可通过主页的联系方式进行指正,谢谢

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值