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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Somnus_k/article/details/82721064

题目:用队列来实现栈。

用两个队列来回倒腾基本就可以了,假设有两个队列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;
	}
	

}

输出:

猜你喜欢

转载自blog.csdn.net/Somnus_k/article/details/82721064