题目:
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
方法一:
用两个栈实现队列,新元素总是压入 s1 的栈顶,同时我们会把 s1 中压入的第一个元素赋值给作为队首元素的 flag 变量。用s2实现出队,s1 中第一个压入的元素在栈底。为了弹出 s1 的栈底元素,我们得把 s1 中所有的元素全部弹出,再把它们压入到另一个栈 s2 中,这个操作会让元素的入栈顺序反转过来。通过这样的方式,s1 中栈底元素就变成了 s2 的栈顶元素,这样就可以直接从 s2 将它弹出了。一旦 s2 变空了,我们只需把 s1 中的元素再一次转移到 s2 就可以了。
class MyQueue {
public int flag;
Stack<Integer> s1;
Stack<Integer> s2;
/** Initialize your data structure here. */
public MyQueue() {
s1=new Stack();
s2=new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
if(s1.empty()){
flag=x;
}
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(s2.isEmpty()){
while(!s1.empty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
/** Get the front element. */
public int peek() {
if(!s2.empty()){
return s2.peek();
}
return flag;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty()&&s2.empty();
}
}
方法二:
用两个栈实现队列,inStack实现入队,outStack实现出队,入队时,outStack的栈顶元素必须始终作为出队的首元素,因此入队时必须判断outStack是否为空,不为空要将outStack中的元素全部出栈从inStack中入栈,然后将元素入队,再将inStack中的所有元素入栈到outStack中。出对时,直接从outStack出栈即可,队首元素即为outStack的栈顶元素。
class MyQueue {
private Stack<Integer> inStack;
private Stack<Integer> outStack;
/** Initialize your data structure here. */
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while (!outStack.empty()) {
inStack.push(outStack.pop());
}
inStack.push(x);
while (!inStack.empty()) {
outStack.push(inStack.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return outStack.pop();
}
/** Get the front element. */
public int peek() {
return outStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return outStack.empty();
}
}