题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
注意插入添加到第二个栈的时候,第二个栈不能有元素,不然会出错,无法保证队列
需要注意的是,当stack2还有元素的时候不能加入,需要一直弹出,弹完之后,再将stack1的元素加入
package com.yzc.offer.JZ9;
import java.util.Stack;
/**
* @author YZC
* @Date 2021/12/3/15:44
*/
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
Integer push = stack1.push(node);
}
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
// Integer pop = null;
// if (!stack2.isEmpty()){
// pop = stack2.pop();
// }
//// pop = stack2.pop();
// return pop;
}
public static void main(String[] args) {
Solution solution = new Solution();
solution.push(2);
solution.push(3);
System.out.println(solution.pop());
solution.push(1);
System.out.println(solution.pop());
System.out.println(solution.pop());
}
}
查看16道真题和解析
搜狐畅游公司福利 1309人发布