使用棧實現隊列的下列操做:java
Implement the following operations of a queue using stacks.python
示例:編程
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
複製代碼
說明:數組
push to top
, peek/pop from top
, size
, 和 is empty
操做是合法的。Notes:bash
push to top
, peek/pop from top
, size
, and is empty
operations are valid.隊列先進後出,棧後進先出。用棧實現隊列,能夠用兩個棧完成題解。入隊列時用 stack1 存入節點,出隊列時 stack1 內節點順序出棧壓入 stack2 中。數據結構
例如 1, 2, 3 元素順序入隊列
即存入棧stack1:[1, 2, 3]
出隊列時順序應爲:1->2->3
可是棧先進先出,出棧順序爲:3->2->1
與出隊列順序不相符
藉助另外一個棧stack2
stack1內的元素順序出棧並壓入stack2
stack1:[1, 2, 3] ---> stack2:[3, 2, 1]
此時stack2出棧順序:1->2->3
與出隊列順序相符
複製代碼
**注意:**在出隊列時無需着急將 stack1 中的節點順序壓入 stack2。由於要實現的隊列是先進後出,能夠將 stack2 中的節點所有彈出以後 再將 stack1 內節點順序壓入stack2,這樣能夠將出棧的時間複雜度攤還到 O(1)。app
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int peek() {
//stack1節點順序彈出並壓入stack2
if (stack2.isEmpty()) {//條件是: stack2爲空,而不是stack1非空, 這樣攤還複雜度O(1)
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());//stack1彈出節點並壓入stack2
}
}
return stack2.peek();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
}
複製代碼
Python語言沒有棧和隊列數據結構,只能用數組 List 或雙端隊列 deque 實現。編程語言
這類編程語言就壓根不須要 用隊列實現棧或用棧實現隊列這種問題,由於棧和隊列自己就必須藉助List、deque實現。spa
因此這道題在這種語言中這就很是簡單了,能夠說是做弊。code
class MyQueue:
def __init__(self):
self.queue = []
def push(self, x: int) -> None:
self.queue.append(x)
def pop(self) -> int:
#彈出第一個元素
return self.queue.pop(0)
def peek(self) -> int:
#返回第一個元素
return self.queue[0]
def empty(self) -> bool:
return not self.queue
複製代碼
歡迎關注微.信公.衆號:愛寫Bug