使用栈实现队列的下列操作:
push(x):将一个元素放入队列的尾部。
pop():从对列首部移除元素。
peek():返回对列首部的元素。
empty():返回队列是否为空
队列特点:先进先出
栈的特点:后进先出
该题转换为后进先出的元素转换为先进先出,使用两个 栈来进行转换
public class Test01 {
public static void main(String[] args) {
MyQueue<String> queue=new MyQueue<String>();
queue.offer("A1");
queue.offer("A2");
queue.offer("A3");
queue.offer("A4");
System.out.println(queue.poll());
System.out.println("-------");
queue.offer("A5");
while(!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
//栈模拟队列
class MyQueue<E>{
private Stack<E> in=new Stack<E>();//入队列
private Stack<E> out=new Stack<E>();//出队列
public boolean isEmpty() {
return in.size()==0&&out.size()==0;
}
public void offer(E e) {
while(!out.isEmpty()) {
in.push(out.pop());
}
in.push(e);
}
// 出队
public E poll() {
while(!in.isEmpty()) {
out.push(in.pop());
}
return out.pop();
}
}