【面试题】两个队列实现一个栈

54 篇文章 0 订阅
44 篇文章 0 订阅

题目:用队列来实现栈。

用两个队列来回倒腾基本就可以了,假设有两个队列A、B,初始都为空,将元素放入队列A中,如果队列B不为空,将B中的元素全部取出放入A中,这样B就为空队列了,然后下次加入元素就加入到B中,如果A不为空就把A中元素全部取出放进B中,这样A就为空队列了,就这样来回倒腾就可以了。可惜面试时候太紧张,脑子转不动,直接说不会了[汗]。

代码:

public class QueueImplStatck {

	Queue<Integer> queue1 = new LinkedList<>();
	Queue<Integer> queue2 = new LinkedList<>();
	public static void main(String[] args) {
		
		QueueimplStatck stack = new QueueimplStatck();
		for (int i = 1; i <=7; i++) {
			stack.push(i);
		}
		while(stack.pop()!=null)
			System.out.print(stack.pop()+" ");
		
	}
	
	void push(int num){
		if(queue1.size()==0)
			{
			queue1.offer(num);
			while(!queue2.isEmpty())
				queue1.offer(queue2.poll());
			}
		if(queue2.size()==0){
			queue2.offer(num);
			while(!queue1.isEmpty())
				queue2.offer(queue1.poll());
		}
		
	}
	
	Integer pop(){
		if(!queue1.isEmpty())
			return queue1.poll();
		else if(!queue2.isEmpty())
			return queue2.poll();
		else
			return null;
	}
	

}

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值