// @lc code=start classMyStack { public: /** Initialize your data structure here. */ MyStack() {
}
/** Push element x onto stack. */ voidpush(int x){ int size = que.size(); que.push(x); for (int i = 0; i < size; ++i) { que.push(que.front()); que.pop(); } }
/** Removes the element on top of the stack and returns that element. */ intpop(){ int res = que.front(); que.pop(); return res; }
/** Get the top element. */ inttop(){ int res = que.front(); return res; }
/** Returns whether the stack is empty. */ boolempty(){ return que.empty(); } private: queue<int> que; };
/** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */ // @lc code=end
classMyStack { public: queue<int> que1; queue<int> que2; // 辅助队列,用来备份 /** Initialize your data structure here. */ MyStack() {
}
/** Push element x onto stack. */ voidpush(int x){ que1.push(x); }
/** Removes the element on top of the stack and returns that element. */ intpop(){ int size = que1.size(); size--; while (size--) { // 将que1 导入que2,但要留下最后一个元素 que2.push(que1.front()); que1.pop(); }
int result = que1.front(); // 留下的最后一个元素就是要返回的值 que1.pop(); que1 = que2; // 再将que2赋值给que1 while (!que2.empty()) { // 清空que2 que2.pop(); } return result; }
/** Get the top element. */ inttop(){ return que1.back(); }
/** Returns whether the stack is empty. */ boolempty(){ return que1.empty(); } };