225. 用隊列實現(xiàn)棧
請你僅使用兩個隊列實現(xiàn)一個后入先出(LIFO)的棧,并支持普通棧的全部四種操作(push、top、pop 和 empty)。
實現(xiàn) MyStack 類:
void push(int x) 將元素 x 壓入棧頂。
int pop() 移除并返回棧頂元素。
int top() 返回棧頂元素。
boolean empty() 如果棧是空的,返回 true ;否則,返回 false 。
?
注意:
你只能使用隊列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 這些操作。
你所使用的語言也許不支持隊列。 你可以使用 list (列表)或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
?
示例:
輸入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 2, 2, false]
解釋:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
?
提示:
1 <= x <= 9
最多調(diào)用100 次 push、pop、top 和 empty
每次調(diào)用 pop 和 top 都保證棧不為空
?
進階:你能否僅用一個隊列來實現(xiàn)棧。
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/implement-stack-using-queues
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。
前天寫的,只寫了使用兩個棧的寫法:
class?MyStack?{
public:
????queue<int>?first;
????queue<int>?second;
????MyStack()?{
????}
????
????void?push(int?x)?{
????????first.push(x);
????}
????
????int?pop()?{
????????int?size?=?first.size();
????????size--;
????????while(size--){
????????????second.push(first.front());
????????????first.pop();
????????}
????????int?ans?=?first.front();
????????first.pop();
????????first?=?second;
????????while(!second.empty()){
????????????second.pop();
????????}
????????return?ans;
????}
????
????int?top()?{
????????return?first.back();
????}
????
????bool?empty()?{
????????return?first.empty();
????}
};