leetcode 232: Implement Queue using Stacks

Use two stacks. Every time I need to pop, I push all numbers in st1 into st2 except the last one, then I pop that one. After that, I push back all numbers into st1. Don't forget to update the front variable.

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        if(st1.empty())
            front=x;
        st1.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        while(st1.size()!=1)
        {
            st2.push(st1.top());
            st1.pop();
        }
        st1.pop();
        if(!st2.empty())
            front=st2.top();
        while(!st2.empty())
        {
            st1.push(st2.top());
            st2.pop();
        }
    }

    // Get the front element.
    int peek(void) {
        return front;
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return st1.empty();
    }
private:
    stack<int> st1;
    stack<int> st2;
    int front;
};


發佈了186 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章