题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
1,元素进栈放入栈A
2,元素出栈
- 如果栈B有元素,则直接栈B出栈。
- 如果栈A有元素,则将栈A的元素全部出栈,并且元素进入栈B,然后栈B出栈。
代码实现
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(stack1.isEmpty()&&stack2.isEmpty()){
throw new RuntimeException("stack is all empty!");
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
网友评论