栈实现队列

使用栈实现队列的下列操作:

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();
	}
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值