连个队列实现一个栈


import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 
 * 两个队列实现一个栈
 * 思路一:q1是专职进出栈的,q2只是个中转站
 *		入栈时:直接入队列q1即可
 *		出栈时:把q1的除最后一个元素外全部转移到队q2中,然后把刚才剩下q1中的那个元素出队列。之后把q2中的全部元素转移回q1中
 * 思路二:q1是专职进出栈的
 *		入栈时:直接入队列q1即可
 *		出栈时:当q2为空,q1不为空时:把q1的除最后一个元素外全部转移到队q2中,然后把刚才剩下q1中的那个元素出队列。
 *			   当q1,q2都为空时,return null 
 *			   当q2不为空,q1为空时,把q2的除最后一个元素外全部转移到队q1中,然后把刚才剩下q2中的那个元素出队列。
 *			   当q1,q2都不为空时,将q1全部加入到q2中,然后把q2的除最后一个元素外全部转移到队q1中,最后把刚才剩下q2中的那个元素出队列。
 */
class T{
	int x;
	public T(int x){
		this.x = x;
	}
	
}
public class Test2 {
	
	Queue<T>q1,q2;
		
	public Test2(){
		q1 = new LinkedBlockingQueue<T>();
		q2 = new LinkedBlockingQueue<T>();
	}
	public void push(T t){
		q1.add(t);
	}
	//思路一
	/*public T pop(){
		T temp = null;
		if(q1.isEmpty()){
			return null;
		}else{
			while(q1.size()!=1){
				q2.add(q1.poll());
			}	
			temp = q1.poll();
			while(!q2.isEmpty()){
				q1.add(q2.poll());
			}
			return temp;
	
		}
	}*/
	
	//思路二
	public T pop(){
		
		T temp = null;
		if(q1.isEmpty()){
			if(q2.isEmpty())
				return null;
			else{
				while(q2.size()!=1){
					q1.add(q2.poll());
				}
				temp = q2.poll();
				return temp;
			}
		}else{
			if(q2.isEmpty()){
			
				while(q1.size()!=1){
					q2.add(q1.poll());
				}
				temp = q1.poll();
				return temp;
			}else{
				while(!q1.isEmpty()){
					q2.add(q1.poll());
				}
				while(q2.size()!=1){
					q1.add(q2.poll());
				}
				temp = q2.poll();
				return temp;
			}
				
		}
	}
	public void display(T t){
		System.out.print(t.x+" ");
	}
	
	public static void main(String[] args){
		Test2  t = new Test2();
		t.push(new T(1));
		t.push(new T(2));
		t.push(new T(3));
		t.display(t.pop());
		t.push(new T(4));
		t.push(new T(5));
		t.display(t.pop());
		t.display(t.pop());
		t.display(t.pop());
		t.display(t.pop());
		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值