
์ค๋์ ๋ฐฑ์ค ์คํ ๋ฌธ์ ์๊ณ ๋ฐฐ์ด์ ์ฌ์ฉํด ์คํ์ ๊ตฌํํ ์ ์์ด์ ์ธ๋ฑ์ค๋ก ์์น๊ฐ์ ํธ๋ํนํ๋๋ก ์์ฑํ๋ค. 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]);
}
}
}
}
}
'์ฝ๋ฉํ ์คํธ > TIL' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[99ํด๋ฝ] 13์ผ์ฐจ ๋ฌธ์ : ํ (0) | 2025.02.06 |
---|---|
[99ํด๋ฝ] 12์ผ์ฐจ ๋ฌธ์ : ๋ง๋๊ธฐ (1) | 2025.02.04 |
[99ํด๋ฝ] 10์ผ์ฐจ ๋ฌธ์ : ํ์ (0) | 2025.01.24 |
[99ํด๋ฝ] 9์ผ์ฐจ ๋ฌธ์ : ์ ์ฃผ ๋ฃ๊ณ ๋ ธ๋ ๋งํ๊ธฐ (0) | 2025.01.23 |
[99ํด๋ฝ] 8์ผ์ฐจ ๋ฌธ์ : ์ ๋ง๋ค ๋ง๋ (1) | 2025.01.22 |
๋๊ธ