classMyQueue { private: stack<int> st; stack<int> tmp_st; public: MyQueue() { } voidpush(int x){ this->st.push(x); } intpop(){ while (!st.empty()) { tmp_st.push(st.top()); st.pop(); } auto res = tmp_st.top(); tmp_st.pop(); // 元素还回 st while (!tmp_st.empty()) { st.push(tmp_st.top()); tmp_st.pop(); }
return res; } intpeek(){ while (!st.empty()) { tmp_st.push(st.top()); st.pop(); } auto res = tmp_st.top(); // tmp_st.pop(); // 元素还回 st while (!tmp_st.empty()) { st.push(tmp_st.top()); tmp_st.pop(); }
/** * 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(); */