题解 | #【模板】队列#

【模板】队列

https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549

双栈实现
public class TemplateQueue {
    public static void main(String[] args) {
        QueueDemo t = new QueueDemo();
        Scanner scan= new Scanner(System.in);
        int val  = Integer.parseInt(scan.nextLine());
        String[] split;
        String next;
        for(int i = 0; i < val;i++){
            next  = scan.nextLine();
            split = next.split(" ");
            if(split[0].equals("pop")){
                t.pop();
            }
            if (split[0].equals("push")){
                t.push(Integer.valueOf(split[1]));
            }
            if (split[0].equals("front")){
                t.front();
            }

        }

    }


}

class QueueDemo{

    Stack<Integer> stackA = new Stack<>();
    Stack<Integer> stackB = new Stack<>();

    public void push(int i){
        stackA.push(i);
    }

    public void pop(){
        //栈b不为空
        if(stackB.size()!=0){
            //弹出栈顶元素即可
            System.out.println(stackB.pop());
            return;
        }
        //说明栈B为空  栈A不为空
        if(stackA.size()!=0){
            while (stackA.size()!=0){
                stackB.push(stackA.pop());
            }
            System.out.println(stackB.pop());
            return;
        }

        //栈A 、栈B均为空
        System.out.println("error");

    }

    public void front(){
        if(stackB.size()!=0){
            System.out.println(stackB.peek());
            return;
        }
        if(stackA.size()!=0){
            while (stackA.size()!=0){
                stackB.push(stackA.pop());
            }
            System.out.println(stackB.peek());
            return;
        }
        System.out.println("error");
    }

全部评论

相关推荐

2025-12-10 19:36
湖北工业大学 Web前端
饿魔:看到在线简历了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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