题解 | #【模板】循环队列#

【模板】循环队列

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

import java.util.*;
public class Main {
    static int first = 0;
    static int last = 0;
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int[] queue = new int[n + 1];
        
        int opts = input.nextInt();
        String line = input.nextLine();
        for (int i = 0; i < opts; i++) {
            line = input.nextLine();
            if ("pop".equals(line)) {
                pop(queue);
            } else if ("front".equals(line)) {
                front(queue);
            } else {
                push(queue, Integer.parseInt(line.substring(5)));
            }
        }
    }
    
    public static void push(int[] queue, int target){
        if(!isFull(queue)){
            last = (last+1)%queue.length;
            queue[last] = target;
        }else{
            System.out.println("full");
        }
    }
    public static void pop(int[] queue){
        if(!isEmpty()){
            first = (first+1)%queue.length;
            System.out.println(queue[first]);
        }else{
            System.out.println("empty");
        }
    }
    public static void front(int[] queue){
        if(!isEmpty()){
            System.out.println(queue[(first+1)%queue.length]);
        }else{
            System.out.println("empty");
        }
    }
    public static boolean isEmpty(){
        return first == last;
    }
    public static boolean isFull(int[] queue){
        return (last+1)%(queue.length) == first;
    }
}

全部评论

相关推荐

秋盈丶:后续:我在宿舍群里和大学同学分享了这事儿,我好兄弟气不过把他挂到某脉上了,10w+阅读量几百条评论,直接干成精品贴子,爽
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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