classMyQueue { public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ voidpush(int x){ while(!s1.empty()) {s2.push(s1.top()); s1.pop();} s1.push(x); while(!s2.empty()) {s1.push(s2.top()); s2.pop();} } /** Removes the element from in front of queue and returns that element. */ intpop(){ int tmp = s1.top(); s1.pop(); return tmp; } /** Get the front element. */ intpeek(){ return s1.top(); } /** Returns whether the queue is empty. */ boolempty(){ return s1.empty(); } private: stack<int> s1, s2; };
/** * 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(); */
classMyQueue { public: /** Initialize your data structure here. */ MyQueue():front(0) { } /** Push element x to the back of queue. */ voidpush(int x){ if(s1.empty()) front = x; s1.push(x); } /** Removes the element from in front of queue and returns that element. */ intpop(){ if(s2.empty()){ while(!s1.empty()) {s2.push(s1.top()); s1.pop();} } int tmp = s2.top(); s2.pop(); return tmp; } /** Get the front element. */ intpeek(){ if(!s2.empty()) return s2.top(); return front; } /** Returns whether the queue is empty. */ boolempty(){ return s1.empty() && s2.empty(); } private: stack<int> s1, s2; int front; };
/** * 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(); */