232. 用棧實現(xiàn)隊列
請你僅使用兩個棧實現(xiàn)先入先出隊列。隊列應(yīng)當(dāng)支持一般隊列支持的所有操作(push、pop、peek、empty):
實現(xiàn) MyQueue 類:
void push(int x) 將元素 x 推到隊列的末尾
int pop() 從隊列的開頭移除并返回元素
int peek() 返回隊列開頭的元素
boolean empty() 如果隊列為空,返回 true ;否則,返回 false
說明:
你 只能 使用標(biāo)準(zhǔn)的棧操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標(biāo)準(zhǔn)的棧操作即可。
?
示例 1:
輸入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 1, 1, false]
解釋:
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
?
提示:
1 <= x <= 9
最多調(diào)用 100 次 push、pop、peek 和 empty
假設(shè)所有操作都是有效的 (例如,一個空的隊列不會調(diào)用 pop 或者 peek 操作)
?
進階:
你能否實現(xiàn)每個操作均攤時間復(fù)雜度為 O(1) 的隊列?換句話說,執(zhí)行 n 個操作的總時間復(fù)雜度為 O(n) ,即使其中一個操作可能花費較長時間。
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/implement-queue-using-stacks
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
題目大意:使用兩個棧實現(xiàn)一個隊列
代碼;
class?MyQueue?{
public:
????stack<int>?stIn;
????stack<int>?stOut;
????MyQueue()?{
????}
????
????void?push(int?x)?{
????????stIn.push(x);
????}
????
????int?pop()?{
????????if(stOut.empty()){
????????????while(!stIn.empty()){
????????????????stOut.push(stIn.top());
????????????????stIn.pop();
????????????}
????????}
????????int?result?=?stOut.top();
????????stOut.pop();
????????return?result;
????}
????
????int?peek()?{
????????int?res?=?this->pop();
????????stOut.push(res);
????????return?res;
????}
????
????bool?empty()?{
????????return?stIn.empty()?&&?stOut.empty();
????}
};
/**
?*?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();
?*/