码迷,mamicode.com
首页 > 其他好文 > 详细

用栈实现队列

时间:2019-09-21 21:33:37      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:from   object   return   通过   rom   队列   initial   ret   turn   

  具体思路:

通过两个栈来模拟

class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int>q1;
    stack<int>q2;
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
       while(!q2.empty()){
           q1.push(q2.top());
           q2.pop();
       }
       q1.push(x);
        while(!q1.empty()){
            q2.push(q1.top());
            q1.pop();
        }
        return ;
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int tmp = 0;
        if(!q2.empty()){
            tmp = q2.top();
            q2.pop();
        }
        return tmp;
    }
    
    /** Get the front element. */
    int peek() {
        int tmp = 0;
        if(!q2.empty()){
            tmp = q2.top();
        }
        return tmp;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return q2.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();
 */

 

用栈实现队列

标签:from   object   return   通过   rom   队列   initial   ret   turn   

原文地址:https://www.cnblogs.com/letlifestop/p/11564493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!