题解 | 【模板】队列

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;
    }
}

全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务