用两个栈实现队列功能

package com.chanmufeng.codingInterviewGuide.stackAndQueue_10;

import java.util.Stack;

/**
 * 用两个栈实现队列功能
 */
public class StackQueue {
    private static Stack<Integer> pushStack;
    private static Stack<Integer> popStack;

    public StackQueue() {
        pushStack = new Stack<>();
        popStack = new Stack<>();
    }

    public static void enqueue(int newNum) {
        pushStack.push(newNum);
    }

    public static int poll() {
        if (pushStack.isEmpty() && popStack.isEmpty()) {
            throw new RuntimeException("queue is empty");
        } else if (popStack.isEmpty()) {
            while (!pushStack.isEmpty()) {
                popStack.push(pushStack.pop());
            }
        }
        return popStack.pop();
    }

    public static int peek() {
        if (pushStack.isEmpty() && popStack.isEmpty()) {
            throw new RuntimeException("queue is empty");
        } else if (popStack.isEmpty()) {
            while (!pushStack.isEmpty()) {
                popStack.push(pushStack.pop());
            }
        }
        return popStack.peek();
    }

    public static void main(String[] args) {

    }
}

全部评论

相关推荐

不亏是提前批,神仙打架,鼠鼠不配了
站队站对牛:现在92都报工艺岗了
投递韶音科技等公司7个岗位
点赞 评论 收藏
分享
炫哥_:为什么都读硕士了?项目还是网上的项目(真心发问)
最后再改一次简历
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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