백준(Java)

[백준] 28278번 '스택2' (자바/JAVA)

심층코드 2025. 4. 30. 03:06

문제

정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 다섯 가지이다.

  1. 1 X: 정수 X를 스택에 넣는다. (1 ≤ X ≤ 100,000)
  2. 2: 스택에 정수가 있다면 맨 위의 정수를 빼고 출력한다. 없다면 -1을 대신 출력한다.
  3. 3: 스택에 들어있는 정수의 개수를 출력한다.
  4. 4: 스택이 비어있으면 1, 아니면 0을 출력한다.
  5. 5: 스택에 정수가 있다면 맨 위의 정수를 출력한다. 없다면 -1을 대신 출력한다.

입력

첫째 줄에 명령의 수 N이 주어진다. (1 ≤ N ≤ 1,000,000)

둘째 줄부터 N개 줄에 명령이 하나씩 주어진다.

출력을 요구하는 명령은 하나 이상 주어진다.

출력

출력을 요구하는 명령이 주어질 때마다 명령의 결과를 한 줄에 하나씩 출력한다.

예제 입력 1 복사

9
4
1 3
1 5
3
2
5
2
2
5

예제 출력 1 복사

1
2
5
3
3
-1
-1

 

코드1

(StringBuilder 사용버전)

 

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

class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        List<Integer> stack = new ArrayList<>();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int command = Integer.parseInt(st.nextToken());

            switch (command) {
                case 1:
                    int value = Integer.parseInt(st.nextToken());
                    stack.add(value);
                    break;
                case 2:
                    if (stack.isEmpty()) {
                        sb.append("-1\n");
                    } else {
                        sb.append(stack.remove(stack.size() - 1)).append("\n");
                    }
                    break;
                case 3:
                    sb.append(stack.size()).append("\n");
                    break;
                case 4:
                    sb.append(stack.isEmpty() ? 1 : 0).append("\n");
                    break;
                case 5:
                    if (stack.isEmpty()) {
                        sb.append("-1\n");
                    } else {
                        sb.append(stack.get(stack.size() - 1)).append("\n");
                    }
                    break;
            }
        }
        System.out.println(sb);
        br.close();
    }
}

코드2 (StringBuilder를 사용하지 않은 버전)

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

class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        List<Integer> stack = new ArrayList<>();

        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int command = Integer.parseInt(st.nextToken());

            switch (command) {
                case 1:
                    int value = Integer.parseInt(st.nextToken());
                    stack.add(value);
                    break;
                case 2:
                    if (stack.isEmpty()) {
                        System.out.println(-1);
                    } else {
                        System.out.println(stack.remove(stack.size() - 1));
                    }
                    break;
                case 3:
                    System.out.println(stack.size());
                    break;
                case 4:
                    System.out.println(stack.isEmpty() ? 1 : 0);
                    break;
                case 5:
                    if (stack.isEmpty()) {
                        System.out.println(-1);
                    } else {
                        System.out.println(stack.get(stack.size() - 1));
                    }
                    break;
            }
        }
        br.close();
    }
}

코드지식

BufferedReader에서의 형변환 명령어 

 

 

String에서 int로 변환: Integer.parseInt(String s)

 

String에서 long으로 변환: Long.parseLong(String s)

 

String에서 double로 변환: Double.parseDouble(String s)

 

String에서 float로 변환: Float.parseFloat(String s)

 

String에서 boolean으로 변환: Boolean.parseBoolean(String s)

 

String에서 byte로 변환: Byte.parseByte(String s)

 

String에서 short로 변환: Short.parseShort(String s)

 

String에서 char로 변환: String 객체의 charAt(int index) 메서드를 사용하여 특정 인덱스의 문자를 얻습니다. 주로 첫 번째 문자를 얻을 때는 charAt(0)을 사용합니다.