题目描述
用两个栈实现队列
算法1
class MyQueue {//栈与队列的区别,在于一个后进先出,一个先进先出,要在出的时候做一个转换。
Stack<Integer> stack1=new Stack<>();//创建两个栈,一个用来存储队列中的信息,一个用来中转。
Stack<Integer> stack2=new Stack<>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {//队列的存储就是栈1的存储,按顺序存在栈1即可。
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {//队列的出队是先进先出,所以出的是存在栈最先进去的数据,这时需要转换,
//通过stack1和stack2的倒换,把stack的top变为应该出的数据,然后进行pop,进行完之后再倒转回stack1.
if(!stack1.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int popValue=stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return popValue;
}
return 0;
}
/** Get the front element. */
public int peek() {
if(!stack1.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int popValue=stack2.peek();//与出队的唯一不同就是这里不需要删除数据,只需要返回数据,所以用peek。
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return popValue;
}
return 0;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.isEmpty();
}
}
/**
* 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();
*/