原题:
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty
题意:用两个栈实现一个队列,需要完成的方法有1 入队;2 出队;3 获取队头元素;4 判断队列是否为空。
思路其实蛮简单的。难点主要是在使用栈模拟入队出队的过程。栈的特点是后进先出,队列的特点是先进先出。我们借助两个栈,一个栈用于存储入队的元素(栈1),另一个栈用于出队操作(栈2)。出队的时候先判断栈2是否为空,如果为空,去栈1判断,说明前面一直在入栈,没有出栈的操作。这时候将栈1中的元素全部出栈,加到栈2中去。这时候,通过栈2的出栈操作,来模拟出队操作。
代码如下:
import java.util.*;
class MyQueue {
/** Initialize your data structure here. */
public MyQueue() {
}
Stack<Integer> stack1 =new Stack();
Stack<Integer> stack2 =new Stack();//题目中要求了,队列中元素为int型
/** Push element x to the back of queue. */
public void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if (stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stack1.isEmpty()){
return stack2.isEmpty();
}
if(stack2.isEmpty()){
return stack1.isEmpty();
}else{
return false;
}
}
}
/**
* 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();
*/