classMyQueue { public: /** Initialize your data structure here. */ MyQueue() {
}
/** Push element x to the back of queue. */ voidpush(int x){ s.push(x); }
/** Removes the element from in front of queue and returns that element. */ intpop(){ adjust(); int res = q.top(); q.pop(); return res; }
/** Get the front element. */ intpeek(){ adjust(); return q.top(); }
/** Returns whether the queue is empty. */ boolempty(){ return s.empty() && q.empty(); }
voidadjust(){ if (q.empty()) { // 这行很重要,不需要每次都调整 while (!s.empty()) { q.push(s.top()); s.pop(); } } }
stack<int> s; stack<int> q; };
/** * 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(); */