上次用栈实现队列,这次反过来
offer()方法往队列尾部插入元素并返回true,队列已满返回false
poll()方法将首个元素从队列中弹出,如果队列是空的,就返回null
peek()方法查看首个元素,不会移除首个元素,如果队列是空的就返回null
java:
用两个队列~
class MyStack {
Queue<Integer> inqueue;
Queue<Integer> outqueue;
public MyStack() {
inqueue=new LinkedList<Integer>();
outqueue=new LinkedList<Integer>();
}
public void push(int x) {
outqueue.offer(x);
while(!inqueue.isEmpty()){
outqueue.offer(inqueue.poll());
}
Queue<Integer> tmp=inqueue;
inqueue=outqueue;
outqueue=tmp;
}
public int pop() {
return inqueue.poll();
}
public int top() {
return inqueue.peek();
}
public boolean empty() {
return inqueue.isEmpty();
}
}
python3:
用一个队列~
for _in range(n)和for each in range(n)是一样的,只不过_在下面不会用到,这里的_可以替换成任何符合规定的字符串
class MyStack:
def __init__(self):
self.queue = collections.deque()
def push(self, x: int) -> None:
n = len(self.queue)
self.queue.append(x)
for _ in range(n):
self.queue.append(self.queue.popleft())
def pop(self) -> int:
return self.queue.popleft()
def top(self) -> int:
return self.queue[0]
def empty(self) -> bool:
return not self.queue