题目来源
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
解题思路
- 用
stack1
作为输入栈 - 用
stack2
作为输出栈。 -
- 如果
stack2
为空,则将stack1
栈的数据全部给stack2
。stack1
的栈底到了stack2
栈顶.
- 如果
-
- 如果
stack2
不为空,则直接pop()
栈顶stack2
的栈顶元素。
- 如果
实现代码
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) { //s1为优先输入栈
stack1.push(node);
}
public int pop() {
//s2为优先输出栈
if(stack2.empty()){ //1.s2为空
while(!stack1.empty()) {
stack2.push(stack1.pop()); //将s2数据全部搬移到s2,s1的栈底到了s2栈顶
}
int temp = stack2.pop(); //取得栈顶元素然后返回
return temp;
} else { //2.s2不为空,直接弹出s2元素
int temp = stack2.pop();
return temp;
}
}
}