题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
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()) {
return stack2.pop();
} else {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
}
解题思想:栈(后进先出)和队列(先进先出)特性。
#算法##算法笔记#
查看17道真题和解析
三奇智元机器人科技有限公司公司福利 70人发布