백준 > 큐

jinvicky·2023년 11월 28일
0

ALG

목록 보기
6/62

큐를 직접 구현하기

import java.io.*;
import java.util.LinkedList;

public class Main {

    private LinkedList<Integer> list = new LinkedList<>();

    public void push(int item) {
        list.add(item);
    }

    public int pop() {
        return list.isEmpty() ? -1 : list.pop();
    }

    public int size() {
        return list.size();
    }

    public int empty() {
        return list.isEmpty() ? 1 : 0;
    }

    public int front() {
        return list.isEmpty() ? -1 : list.getFirst();
    }

    public int back() {
        return list.isEmpty() ? -1 : list.getLast();
    }

    public static void main(String[] args) throws IOException {

        Main customQ = new Main();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        while (N-- > 0) {
            String order = br.readLine();
            String[] params = order.split(" ");

            switch (params[0]) {
                case "push":
                    customQ.push(Integer.parseInt(params[1])); //명령어 파람
                    break;
                case "front":
                    bw.append(customQ.front() + "\n");
                    break;
                case "back":
                    bw.append(customQ.back() + "\n");
                    break;
                case "size":
                    bw.append(customQ.size() + "\n");
                    break;
                case "pop":
                    bw.append(customQ.pop() + "\n");
                    break;
                case "empty":
                    bw.append(customQ.empty() + "\n");
                    break;
            }
        }
        bw.flush();
        bw.close();
    }
}

결과

성공

구현과 로직은 머리 안에 있었는데 문제를 제대로 안 읽어서 헤맸다.
push는 print하면 안되고 문제 제출할 때 클래스명과 제출할 때 문제 확인하는 걸 잊었다;;

기타

push x와 같은 명령어의 경우 명령어와 파람을 분리해야 하는데 기존에는 chr.charAt(int idx) 메서드를 썼는데 이번에는 String[]에 " "를 구분자로 해서 담아서 사용했다. 이쪽이 더 낫다고 생각한다.

문제 풀이 소요 시간

1시간 내

profile
일단 쓰고 본다

0개의 댓글