18258 큐 2 (JAVA)

Fekim·2022년 3월 7일
0

ps

목록 보기
36/48
  • 입력을 Scanner로 받으면 시간초과가 발생하는 문제
  • BufferedReader로 받으면 통과!
public class Main {
    static class Queue{
        public int front;
        public int rear;
        public int[] item;
        public Queue(int size) {
            this.front = -1;
            this.rear = -1;
            this.item = new int[size];
        }
        public void push(int item){
            this.item[++rear] = item;
        }
        public int pop(){
            if(this.front == this.rear)
                return -1;
            else
                return this.item[++front];
        }
        public int size(){
            return rear - front;
        }
        public int empty(){
            if(this.front == this.rear)
                return 1;
            else
                return 0;
        }
        public int front(){
            if(front==rear)
                return -1;
            else
                return this.item[front+1];
        }
        public int back(){
            if(front==rear)
                return -1;
            else
                return this.item[rear];
        }

    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int n = Integer.parseInt(br.readLine());
        Queue q = new Queue(n);

        while(n --> 0){
            String cmd = br.readLine();
            if(cmd.equals("front"))
                sb.append(q.front()).append('\n');
            else if(cmd.equals("back"))
                sb.append(q.back()).append('\n');
            else if(cmd.equals("size"))
                sb.append(q.size()).append('\n');
            else if(cmd.equals("pop"))
                sb.append(q.pop()).append('\n');
            else if(cmd.equals("empty"))
                sb.append(q.empty()).append('\n');
            else{
                String[] cmd_arr = cmd.split(" ");
                q.push(Integer.parseInt(cmd_arr[1]));
            }
        }
        System.out.println(sb);
    }
}
profile
★Bugless 2024★

0개의 댓글