美文网首页
12.Implement Queue using Stacks

12.Implement Queue using Stacks

作者: Anaven | 来源:发表于2017-01-02 16:54 被阅读0次

    https://leetcode.com/problems/implement-queue-using-stacks/

    class Queue {
    public:
        stack<int> s1;
        stack<int> s2;
        
        // Push element x to the back of queue.
        void push(int x) {
            s1.push(x);
        }
    
        // Removes the element from in front of queue.
        void pop(void) {
            if (s2.empty()){
                adjust();
            }
            int val = s2.top();
            s2.pop();
        }
    
        // Get the front element.
        int peek(void) {
            if (s2.empty()) {
                adjust();
            }
            return s2.top();
        }
    
        // Return whether the queue is empty.
        bool empty(void) {
            return s1.empty() && s2.empty();
        }
        
        void adjust() {
            if (s1.empty()) {
                return;
            }
            
            while (!s1.empty()) {
                s2.push(s1.top());
                s1.pop();
            }
        }
    };
    

    相关文章

      网友评论

          本文标题:12.Implement Queue using Stacks

          本文链接:https://www.haomeiwen.com/subject/mqwwvttx.html