题目描述
用两个栈来实现一个队列,完成队列的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
stack1.add(node);
}
public int pop() {//出队操作
if(stack2.isEmpty()){//stack2为空
while(!stack1.isEmpty()){//stack1非空,将其中的元素弹出,然后压入stack2
stack2.add(stack1.pop());
}
}
return stack2.pop();//stack2非空,弹出其中元素
}
}
本文介绍了一种使用两个栈来实现队列的方法。通过将入队操作直接压入第一个栈,而出队操作则先判断第二个栈是否为空,若为空则将第一个栈的所有元素依次弹出并压入第二个栈,最后从第二个栈中弹出元素完成出队操作。
452

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



