🌻题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
🌻思路:定义A栈、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) {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
}