์ฝ๋ฉํ
์คํธ/TIL
[99ํด๋ฝ] 11์ผ์ฐจ ๋ฌธ์ : ์คํ
moon101
2025. 2. 3. 22:42
์ค๋์ ๋ฐฑ์ค ์คํ ๋ฌธ์ ์๊ณ ๋ฐฐ์ด์ ์ฌ์ฉํด ์คํ์ ๊ตฌํํ ์ ์์ด์ ์ธ๋ฑ์ค๋ก ์์น๊ฐ์ ํธ๋ํนํ๋๋ก ์์ฑํ๋ค. 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]);
}
}
}
}
}