在复习数据结构的栈和队列内容时,老师给我们抛出了一个问题:如何用两个栈实现一个队列,故作此文。
算法思想
由于栈结构的特点是先入后出,队列的特点是先进先出,用两个栈实现一个队列就可以用这种方式:

代码实现
public class TwoStacksToOneQueue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
void push(int n){
stack1.push(n);
}
int pop(){
if(stack2.size()!=0){
while(!stack2.isEmpty()){
int temp = stack1.peek();
stack2.push(temp);
stack1.pop();
}
}
int a = stack2.peek();
stack2.pop();
return a;
}
}
本文详细阐述了如何利用栈的特性,通过构建两个栈来模拟队列的先进先出行为,通过代码实现和算法思路剖析,帮助读者理解数据结构在实际问题中的应用。

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



