题解 | 【模板】队列

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        ArrayQueue queue1 = new ArrayQueue(n);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            String arr[] = str.split(" ");
            if(arr[0].equals("push")){
                queue1.offer(Integer.parseInt(arr[1]));
            }else if(arr[0].equals("pop")){
                queue1.poll();
            }else{
                queue1.peek();
            }
        }
    }
}

class ArrayQueue {
    private int head = 0;
    private int tail = 0;
    private final int[] array;
    private final int length;

    public ArrayQueue(int capacity) {
        length = capacity + 1;
        array = new int[length];
    }

    public void offer(int value) {
        if (isFull()) {
            System.out.println("error");
        } else {
            array[tail] = value;
            tail = (tail + 1) % length;
        }
    }

    public void poll() {
        if (isEmpty()) {
            System.out.println("error");
            return;
        } else {
            int value = array[head];
            head = (head + 1) % length;
            System.out.println(value);
        }
    }
    public void peek() {
        if (isEmpty()) {
            System.out.println("error");
            return;
        } else {
            System.out.println(array[head]);
        }
    }
    public boolean isEmpty() {
        return tail == head;
    }
    public boolean isFull() {
        return (tail + 1) % length == head;
    }
}

全部评论

相关推荐

01-11 02:09
已编辑
华中师范大学 golang
京京洪洪学java:如果坚定转Java就要先做好暑期结果可能没那么好的准备,大厂也有做go的,也有接受内部切换技术栈的,go怎么就不行了呢?,ACM+华师肯定能接到一些大厂面试的,acm铜的基础可以让你比较轻松地应对中大厂的手撕,就是八股和项目要下硬功夫,至于找不到go项目?github上一直刷啊,跟刷b站主页一样,那么多好的go开源项目,怎么会找不到呢?刷到想学感兴趣的用ai吃透,试着改进或者吸收作为自己的项目,另一个选择就是考研了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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