题解 | 【模板】队列操作

【模板】队列操作

https://www.nowcoder.com/practice/1137c8f6ffac4d5d94cc1b0cb08723f9

方法一 使用LinkedList

import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            int chose = in.nextInt();
            switch (chose) {
                case 1:
                    queue.offer(in.nextInt());
                    break;
                case 2:
                    if (queue.isEmpty()) {
                        System.out.println("ERR_CANNOT_POP");
                    } else {
                        queue.poll();
                    }
                    break;
                case 3:
                    if (queue.isEmpty()) {
                        System.out.println("ERR_CANNOT_QUERY");
                    } else {
                        System.out.println(queue.peek());
                    }
                    break;
                case 4:
                    System.out.println(queue.size());

            }

        }

    }
}

方法二 使用ArrayDeque

import java.util.Scanner;
import java.util.Queue;
import java.util.ArrayDeque;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Queue<Integer> queue = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            int chose = in.nextInt();
            switch (chose) {
                case 1:
                    queue.add(in.nextInt());
                    break;
                case 2:
                    if (queue.isEmpty()) {
                        System.out.println("ERR_CANNOT_POP");
                    } else {
                        queue.poll();
                    }
                    break;
                case 3:
                    if (queue.isEmpty()) {
                        System.out.println("ERR_CANNOT_QUERY");
                    } else {
                        System.out.println(queue.peek());
                    }
                    break;
                case 4:
                    System.out.println(queue.size());

            }

        }

    }
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

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