코테

백준 10828 스택 구현하기

SigLee0505 2023. 4. 18. 17:20

문제 설명

문제 풀이

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

/*
* 스택 직접 구현하기
* push 스택에 새로운 데이터 추가
* pop 스택에 있는 가장 위에 있는 것 제거
* size  스택에 들어있는 정수 갯수
* empty 스택이 비어 있으면 1 아니면 0
* top  스택 최상단에 있는 정수 출력
*
* */
public class Backjoon10828 {
    static List<Integer> list = new ArrayList<>();

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

        int numberOfNotices = Integer.parseInt(br.readLine());

        for (int i = 0; i < numberOfNotices; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine()," ");
            choiceMethod(st);
        }

    }

    private static void choiceMethod(StringTokenizer st) {
        switch (st.nextToken()) {
            case "push" :
                push(Integer.parseInt(st.nextToken()));
                return;
            case "pop":
                System.out.println(pop());
                return;
            case "top":
                System.out.println(top());; return;
            case "size":
                System.out.println(size());;return;
            default :
                System.out.println(empty());; return;
        }
    }

    private static void push(int num) {
        list.add(num);
    }
    private static int pop(){
        return !list.isEmpty() ?  list.remove(list.size()-1) : -1;
    }

    private static int top() {
        return !list.isEmpty() ? list.get(list.size()-1) : -1;
    }

    private static int size() {
        return !list.isEmpty() ? list.size() : 0;
    }

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

내가 풀었던 문제다
처음 문제를 풀 때는 만약 push 보다 pop 이 더많을 때나 빈 스택에 top을 가져와야할 때에 대한 예외처리를 하지 않았었다.
당근 이런건 문제에서 그냥 넘겼겠지.. 하는 마음에 그냥 넘겼었는데 이것 때문에 문제가 많이 발생했다.

그래서 위에 있는 모든 조건들을 보면 예외처리가 전부 되어있다.

배열로 만들어도 좋지만 뭔가 배열보다는 리스트를 사용하는게 좀 더 기분이가 좋은 것 같다.

'코테' 카테고리의 다른 글

백준 1697  (0) 2023.05.04
백준 7569  (0) 2023.05.04
백준 4949 java  (0) 2023.04.19
백준 11720 JAVA  (0) 2023.04.18
백준 1546 JAVA  (0) 2023.04.18