用2个栈实现队列
描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
解析
其实就是将栈的先进后出,变为队列的先进先出。
stack1用来入栈。当push stack1时,将stack1的所有元素放到stack2,直到stack1为空。再将新值push进去,再将stack2的所有值再push回来到stack1。
代码
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { if (stack1.isEmpty()) { stack1.push(node); } else { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } stack1.push(node); while (!stack2.isEmpty()) { stack1.push(stack2.pop()); } } } public int pop() { //这里注意下返回值为null的情况,不能转为int return stack1.pop(); } }

更多精彩