题解 | 【模板】循环队列

【模板】循环队列

https://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n=0, q=0;
        // 注意 hasNext 和 hasNextLine 的区别
        if(in.hasNextLine()){
            String line = in.nextLine();
            String []arr = line.split(" ");
            n = Integer.parseInt(arr[0]);
            q = Integer.parseInt(arr[1]);
        }
        Queue queue = new Queue(n);
        while ((q-- > 0) && in.hasNextLine()) {
            String line = in.nextLine();
            String[] arr = line.split(" ");
            String operation = arr[0];
            try {
                if (operation.equals("push")) {
                    queue.push(Integer.parseInt(arr[1]));
                } else if (operation.equals("pop")) {
                    System.out.println(queue.pop());
                } else if (operation.equals("front")) {
                    System.out.println(queue.front());
                } else {
                    System.out.println("其他的非法操作");
                }
            } catch (RuntimeException e) {
                //e.printStackTrace();                
                System.out.println(e.getMessage());
            } 
        }

    }
}

class Queue {
    int[] arr;
    int index = -1;

    Queue() {
        arr = new int[16];
    }

    Queue(int n) {
        arr = new int[n];
    }

    public void push(int x) {
        if (index + 2 > arr.length) {
            throw new RuntimeException("full");
        }
        arr[++index] = x;
    }

    public String front() {
        if (index == -1) {
            throw new RuntimeException("empty");
        }
        return Integer.toString(arr[0]);
    }

    public String pop() {
        if (index == -1) {
            throw new RuntimeException("empty");
        }
        String top = Integer.toString(arr[0]);
        for (int i = 1; i <= index; ++i) {
            arr[i - 1] = arr[i];
        }
        index -= 1;

        return top;
    }
}

全部评论

相关推荐

Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务