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());
}
}
连个队列实现一个栈
最新推荐文章于 2023-02-28 12:58:31 发布