题目:用两个栈来实现一个队列,完成队列的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.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}return stack2.pop();
}
}
}
本文介绍了一种使用两个栈来实现队列的方法,通过代码示例详细解释了如何完成队列的基本操作,如Push和Pop。此方法巧妙地利用了栈的特性,实现了队列的先进先出(FIFO)原则。

3521

被折叠的 条评论
为什么被折叠?



