๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ฝ”๋”ฉํ…Œ์ŠคํŠธ/TIL

[99ํด๋Ÿฝ] 11์ผ์ฐจ ๋ฌธ์ œ: ์Šคํƒ

by moon101 2025. 2. 3.

 

์˜ค๋Š˜์€ ๋ฐฑ์ค€ ์Šคํƒ ๋ฌธ์ œ์˜€๊ณ  ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•ด ์Šคํƒ์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์ธ๋ฑ์Šค๋กœ ์œ„์น˜๊ฐ’์„ ํŠธ๋ž˜ํ‚นํ•˜๋„๋ก ์ž‘์„ฑํ–ˆ๋‹ค. sc.nextInt()๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ๋‚˜๋ฉด \n ๊ฐœํ–‰๋ฌธ์ž๊ฐ€ ๋‚จ์•„์žˆ์–ด์„œ sc.nextLine()์œผ๋กœ ํ•œ ๋ฒˆ  ํ˜ธ์ถœํ•ด์„œ ๋ฒ„ํผ์—์„œ ๊ฐœํ–‰๋ฌธ์ž๋ฅผ ์ œ๊ฑฐ ํ•ด์ค€ ๋‹ค์Œ์— ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๋ถ€๋ถ„์ด ๋‚˜๋ฆ„ ์–ด๋ ค์› ๋‹ค. 

 

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       
        int N = sc.nextInt();
        sc.nextLine();
        
        String[] stack = new String[N];
        
        int idx = -1;
        for (int i = 0; i < N; i++) {
            String[] s = sc.nextLine().split(" ");
            
            if (s[0].equals("push")) {
                stack[++idx] = s[1];
            } else if (s[0].equals("pop")) {
                if (idx == -1) {
                    System.out.println(-1);
                } else {
                    System.out.println(stack[idx--]);
                }
            } else if (s[0].equals("size")) {
                System.out.println(idx + 1);
            } else if (s[0].equals("empty")) {
                int result = (idx == -1 ? 1 : 0);
                System.out.println(result);
            } else if (s[0].equals("top")) {
                if(idx == -1) {
                    System.out.println(-1);
                } else {
                    System.out.println(stack[idx]);
                }
            }
        }
    }
}
 
 

๋Œ“๊ธ€