标签:时间 elf init java not OLE empty deque queue
使用栈实现队列的下列操作:
示例:
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
操作是合法的。首先了解下栈和队列的特点:
所以我们只用一个栈的话是无法实现队列的操作的。不妨换个思路,我们用两个栈来实现队列:
当栈2不为空时直接 pop,否则把栈1的所有元素放到栈2然后执行栈2 pop 操作。
java描述
import java.util.Stack;
class MyQueue {
/** Initialize your data structure here. */
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (!s2.isEmpty()) return s2.pop();
while (!s1.isEmpty()) {
int val = s1.pop();
s2.push(val);
}
return s2.pop();
}
/** Get the front element. */
public int peek() {
if (!s2.isEmpty()) return s2.peek();
while (!s1.isEmpty()) {
int val = s1.pop();
s2.push(val);
}
return s2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty() && s2.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();
* boolean param_4 = obj.empty();
*/
python3描述
from collections import deque
class Stack:
def __init__(self):
self.items = deque()
def push(self, val):
return self.items.append(val)
def pop(self):
return self.items.pop()
def top(self):
return self.items[-1]
def empty(self):
return len(self.items) == 0
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.s1 = Stack()
self.s2 = Stack()
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.s1.push(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if not self.s2.empty():
return self.s2.pop()
while not self.s1.empty():
val = self.s1.pop()
self.s2.push(val)
return self.s2.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if not self.s2.empty():
return self.s2.top()
while not self.s1.empty():
val = self.s1.pop()
self.s2.push(val)
return self.s2.top()
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self.s1.empty() and self.s2.empty()
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
可以看出,java支持栈,我们可以直接调用java.util.Stack
,而 python 不支持栈,我们可以自己使用 deque
(双端队列),来模拟一个栈。时间和内存对比如下:
标签:时间 elf init java not OLE empty deque queue
原文地址:https://www.cnblogs.com/weixuqin/p/10812351.html