請(qǐng)你僅使用兩個(gè)棧實(shí)現(xiàn)先入先出隊(duì)列超埋。隊(duì)列應(yīng)當(dāng)支持一般隊(duì)列支持的所有操作(push续膳、pop题山、peek、empty):
實(shí)現(xiàn) MyQueue 類(lèi):
void push(int x) 將元素 x 推到隊(duì)列的末尾
int pop() 從隊(duì)列的開(kāi)頭移除并返回元素
int peek() 返回隊(duì)列開(kāi)頭的元素
boolean empty() 如果隊(duì)列為空焊唬,返回 true 恋昼;否則,返回 false
說(shuō)明:
你只能使用標(biāo)準(zhǔn)的棧操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的赶促。
你所使用的語(yǔ)言也許不支持棧液肌。你可以使用 list 或者 deque(雙端隊(duì)列)來(lái)模擬一個(gè)棧,只要是標(biāo)準(zhǔn)的棧操作即可鸥滨。
進(jìn)階:
你能否實(shí)現(xiàn)每個(gè)操作均攤時(shí)間復(fù)雜度為 O(1) 的隊(duì)列嗦哆?換句話說(shuō),執(zhí)行 n 個(gè)操作的總時(shí)間復(fù)雜度為 O(n) 婿滓,即使其中一個(gè)操作可能花費(fèi)較長(zhǎng)時(shí)間老速。
示例:
輸入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 1, 1, false]
解釋?zhuān)?br>
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è)所有操作都是有效的 (例如橘券,一個(gè)空的隊(duì)列不會(huì)調(diào)用 pop 或者 peek 操作)
java代碼:
class MyQueue {
private Stack<Integer> queue1;
private Stack<Integer> queue2;
/** Initialize your data structure here. */
public MyQueue() {
queue1 = new Stack<>();
queue2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
queue1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int x = 0;
while(!queue1.isEmpty()){
x = queue1.pop();
if(!queue1.isEmpty()){
queue2.push(x);
}
}
while(!queue2.isEmpty()){
queue1.push(queue2.pop());
}
return x;
}
/** Get the front element. */
public int peek() {
int x = 0;
while(!queue1.isEmpty()){
x = queue1.pop();
queue2.push(x);
}
while(!queue2.isEmpty()){
queue1.push(queue2.pop());
}
return x;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/