题解 | #用两个栈实现队列#

用两个栈实现队列

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());

    }
}


全部评论

相关推荐

06-07 12:20
新余学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务