题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.size()==0){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
if (stack2.size() == 0) {//当stack1和stack2都长度为0的时候,运行到这里还是会出现stack2的长度为0,所以要做异常处理
System.out.println("stack1和stack2的长度都为0,不能进行pop操作,抛出异常");
return -1;
}
return stack2.pop();
}
}
测试案例:
import java.util.Stack;
public class QueuesToStack
{
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.size()==0){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
if (stack2.size() == 0) {//当stack1和stack2都长度为0的时候,运行到这里还是会出现stack2的长度为0,所以要做异常处理
System.out.println("stack1和stack2的长度都为0,不能进行pop操作,抛出异常");
return -1;
}
return stack2.pop();
}
public static void main(String[] args)
{
QueuesToStack stack=new QueuesToStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(5);
stack.push(6);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
输出:
1
2
3
4
5
6
stack1和stack2的长度都为0,不能进行pop操作,抛出异常
-1