LeetCode 用栈实现队列:使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
思路:双栈实现。从 in 栈入数据,从 out 栈出数据,当需要获取队首元素或者移除队首元素时,先判断 out 栈是否为空,如果不为空,直接操作。如果为空,需要先将 in 栈的数据一个一个移入 out 栈,这样数据在 out 栈中就是期待的样子。
import java.util.Stack;
/*E push(E item) 压栈
E pop() 出栈
E peek() 查看栈顶元素
boolean empty() 判断栈是否为空 */
public class MyQueue {
private Stack<Integer> in;
private Stack<Integer> out;
/** 初始化 */
public MyQueue() {
in = new Stack();
out = new Stack();
}
/** 将一个元素放入队列的尾部 */
public void push(int x) {
in.push(x);
}
/** 从队列首部移除元素*/
public int pop() {
if(out.isEmpty()){
while(in.size() != 0){
int tmp = in.pop();
out.push(tmp);
}
}
return out.pop();
}
/** 返回队列首部的元素*/
public int peek() {
if(out.isEmpty()){
while(in.size() != 0){
int tmp = in.pop();
out.push(tmp);
}
}
int v = out.pop();
out.push(v);
return v;
}
/**返回队列是否为空*/
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
System.out.println(queue.peek()); // 返回 1
System.out.println(queue.pop() ); // 返回 1
System.out.println(queue.empty()); // 返回 false
}
}