import java.util.LinkedList;
import java.util.Queue;
//两个队列实现一个栈,想象以下是一个栈
public class StackByQuene {
Queue<Integer> queue1=new LinkedList<>();
Queue<Integer> queue2=new LinkedList<>();
public void push(int node) //第一次入栈queue2,下一次入栈非空的队列,
{
if(!queue1.isEmpty())
queue1.offer(node);
else
queue2.offer(node);
}
public Integer pop() //哪个不为空,哪个出栈到另一个里面,留下最后一个node,就是出栈
{
if(!queue1.isEmpty()&&queue2.isEmpty())
{
while(queue1.size()>1)
{
queue2.offer( queue1.poll());
}
return queue1.poll();
}
if(queue1.isEmpty()&&!queue2.isEmpty())
{
while(queue2.size()>1)
{
queue1.offer(queue2.poll());
}
return queue2.poll();
}
return null;
}
@Override
public String toString() {
return "StackQuene{" +
"queue1=" + queue1 +
", queue2=" + queue2 +
'}';
}
public static void main(String[] args) {
StackByQuene s=new StackByQuene();
s.push(1);
s.push(2);
s.push(3);
System.out.println(s);
s.pop();
System.out.println(s);
s.push(4);
s.push(5);
System.out.println(s);
s.pop();
System.out.println(s);
}
}
两个队列实现一个栈
于 2022-08-07 17:18:54 首次发布