232. 用棧實(shí)現(xiàn)隊(duì)列
請(qǐng)你僅使用兩個(gè)棧實(shí)現(xiàn)先入先出隊(duì)列。隊(duì)列應(yīng)當(dāng)支持一般隊(duì)列的支持的所有操作(push、pop、peek、empty):
實(shí)現(xiàn) MyQueue 類:
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]
解釋:
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
題解
可以把一個(gè)棧當(dāng)做「輸入?!梗蚜硪粋€(gè)棧當(dāng)做「輸出?!?。
當(dāng) push() 新元素的時(shí)候,放到「輸入?!沟臈m?,記此順序?yàn)椤篙斎胄颉埂?br>
當(dāng) pop() 元素的時(shí)候,是從「輸出?!箯棾鲈?。如果「輸出?!篂榭眨瑒t把「輸入?!沟脑刂饌€(gè) pop() 并且 push() 到「輸出棧」中,這一步會(huì)把「輸入棧」的棧底元素放到了「輸出?!沟臈m?。此時(shí)負(fù)負(fù)得正,從「輸出?!沟?pop() 元素的順序與「輸入序」相同。
class MyQueue {
private Deque<Integer> stack1;
private Deque<Integer> stack2;
/**
* Initialize your data structure here.
*/
public MyQueue() {
stack1 = new ArrayDeque<>();
stack2 = new ArrayDeque<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
stack1.addLast(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.addFirst(stack1.pollLast());
}
}
return stack2.pollFirst();
}
/**
* Get the front element.
*/
public int peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.addFirst(stack1.pollLast());
}
}
return stack2.peekFirst();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
}