用栈实现队列—Java:
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
解析:
使用两个栈实现队列,一个作为专门的入队列,一个作为出队列。
import java.util.ArrayList;
/**
* Create with Darcula IDEA
* Description:
* 用栈实现队列
*/
public class MyQueue {
private ArrayList<Integer> in;
private ArrayList<Integer> out;
/** Initialize your data structure here. */
public MyQueue() {
in = new ArrayList<>();
out = new ArrayList<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
in.add(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while(out.isEmpty()){
int size = in.size();
for(int i = 0; i < size;i++){
int v = in.remove(in.size() - 1);
out.add(v);
}
}
return out.remove(out.size()-1);
}
/** Get the front element. */
public int peek() {
while(out.isEmpty()){
int size = in.size();
for(int i = 0; i < size; i++){
int v = in.remove(in.size()-1);
out.add(v);
}
}
return out.get(out.size()-1);
}
/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.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();
*/