题目描述
用两个栈来实现一个队列,完成队列的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。这种方法巧妙地利用了栈的特性,解决了队列的数据结构实现问题。
392

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



