1. 题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
2. 解题思路
- 入队:将元素进栈A
- 出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B。
- 如果栈B不为空,栈B出栈。
3. 代码
public class TwoStackImplementationQueues {
public static Stack<Integer> stack1 = new Stack<Integer>();
public static Stack<Integer> stack2 = new Stack<Integer>();
public static void main(String [] args){
TwoStackImplementationQueues mm=new TwoStackImplementationQueues();
for (int i=0;i<5;i++){
mm.push(i);
}
while(true){
System.out.println(mm.pop());
}
}
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue is empty!");
}
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
运行:
0
1
2
3
4
Exception in thread "main" java.lang.RuntimeException: Queue is empty!
4. 两个队列实现栈
解题思路:
- 在push的时候,把元素向非空的队列内添加
- 在pop的时候,把不为空的队列中的size()-1个元素poll出来,添加到另为一个为空的队列中,再把队列中最后的元素poll出来
- 两个队列在栈不为空的情况下始终是有一个为空,另一个不为空的。push添加元素到非空的队列中,pop把非空队列的元素转移到另一个空的队列中,直到剩下最后一个元素,这个元素就是要出栈的元素(最后添加到队列中的元素)。
- 最终两个队列都为空,这里其实只是利用队列的先进先出做了一个中间转换。
代码;
import java.util.LinkedList;
import java.util.Queue;
public class TwoQueuesImplementStack {
private static Queue<Object> queue1=new LinkedList<Object>();
private static Queue<Object> queue2=new LinkedList<Object>();
public static void main(String[] args) {
TwoQueuesImplementStack mm =new TwoQueuesImplementStack();
for (int i=0;i<5;i++){
mm.push(i);
}
System.out.println("..............");
while(true){
mm.pop();
}
}
// 向队列中执行入栈操作时,把元素添加到非空的队列中
public void push(Object item){
if(!queue1.isEmpty())
queue1.offer(item);
else
queue2.offer(item);
System.out.println("入栈元素为:"+item);
}
public void pop(){
if((!queue1.isEmpty())||(!queue2.isEmpty())){
if(queue1.isEmpty()){
while(queue2.size()>1){
queue1.offer(queue2.poll());
}
System.out.println("出栈元素为:"+queue2.poll());
}else{
while(queue1.size()>1){
queue2.offer(queue1.poll());
}
System.out.println("出栈元素为:"+queue1.poll());
}
}
else
throw new RuntimeException("栈为空,无法执行出栈操作");
}
}
运行:
入栈元素为:0
入栈元素为:1
入栈元素为:2
入栈元素为:3
入栈元素为:4
..............
出栈元素为:4
出栈元素为:3
出栈元素为:2
出栈元素为:1
出栈元素为:0
Exception in thread "main" java.lang.RuntimeException: 栈为空,无法执行出栈操作
以上是学习笔记,进攻参考。