解释: MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
// @lc code=start classMyQueue { public: /** Initialize your data structure here. */ MyQueue() {
}
/** Push element x to the back of queue. */ voidpush(int x){ stackIn.push(x); }
/** Removes the element from in front of queue and returns that element. */ intpop(){ if (stackOut.empty()) { // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据) while (!stackIn.empty()) { stackOut.push(stackIn.top()); stackIn.pop(); } } int res = stackOut.top(); stackOut.pop(); return res; }
/** Get the front element. */ intpeek(){ // 直接使用已有的pop函数 int res = this->pop(); stackOut.push(res); return res; }
/** Returns whether the queue is empty. */ boolempty(){ return stackIn.empty() && stackOut.empty(); } private: stack<int> stackIn; stack<int> stackOut; };
/** * 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(); */ // @lc code=end