版权声明:Mr.Wang 汪先生版权所有,谢绝任何转载 https://blog.csdn.net/weixin_37650458/article/details/87073053
1.题目
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 思路:栈只能先进后出,队列是先进先出,所以两个栈保存元素,一个正着放,一个反着放
package com.wx.concurrent11;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Queue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
if (stack1.empty() && stack2.empty()) {
stack1.push(node);
stack2.push(node);
} else {
List<Integer> list = new ArrayList<Integer>();
stack1.push(node);
while (!stack1.empty()) {
Integer pop = stack1.pop();
list.add(pop);
}
while (!stack2.empty()) {
stack2.pop();
}
for (Integer integer : list) {
stack2.push(integer);
}
for (int i = list.size() - 1; i >= 0; i--) {
stack1.push(list.get(i));
}
}
}
public int pop() {
/***弹出栈就是要弹出反着放的值*/
List<Integer> list = new ArrayList<Integer>();
while (!stack1.empty()) {
list.add(stack1.pop());
}
for (int i = list.size() - 1; i > 0; i--) {
stack1.push(list.get(i));
}
return stack2.pop();
}
}
测试:
Queue queue=new Queue();
queue.push(1);
queue.push(2);
queue.push(3);
System.out.println(queue.pop()); //1
System.out.println(queue.pop()); //2
System.out.println(queue.pop()); //3
queue.push(4);
System.out.println(queue.pop()); //4
queue.push(5);
System.out.println(queue.pop()); //5
System.out.println(queue.pop());
结果:和预期的一致,但是在线运行就是不过。
然后再看一下别人写的,就很简洁了。首先添加元素都放在stack1,弹出方法的时候把stack1都弹出来放在stack2,然后stack2弹出元素,完成队列弹出方法,push方法的时候,又把剩余stack2元素都弹出来放在stack1再push新元素即可。
package com.wx.concurrent11;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Queue1 {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
/***弹出栈就是要弹出反着放的值*/
if (stack1.empty()&&stack2.empty()){
throw new RuntimeException("Queue null");
}
while (!stack1.empty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
结果和预期的一致: