[BaekJoon] 28278번 - 스택 2 [Java][C++]
[BaekJoon] 28278번 - 스택 2 [Java][C++]
1. 문제 풀이
스택 자료구조를 구현하는 문제로 배열을 활용해서 구현했다.
2. 코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int[] stack = new int[1000000];
int peek = -1;
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
int command = Integer.parseInt(st.nextToken());
if (command == 1) {
int x = Integer.parseInt(st.nextToken());
stack[++peek] = x;
} else if (command == 2) {
if (peek == -1) {
sb.append("-1\n");
} else {
sb.append(stack[peek--]).append("\n");
}
} else if (command == 3) {
sb.append(peek + 1).append("\n");
} else if (command == 4) {
if (peek == -1) {
sb.append("1\n");
} else {
sb.append("0\n");
}
} else {
if (peek == -1) {
sb.append("-1\n");
} else {
sb.append(stack[peek]).append("\n");
}
}
}
System.out.println(sb);
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int stack[1000000];
int peek = -1;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int command;
cin >> command;
if (command == 1) {
int x;
cin >> x;
stack[++peek] = x;
} else if (command == 2) {
if (peek == -1) {
cout << -1 << '\n';
} else {
cout << stack[peek--] << '\n';
}
} else if (command == 3) {
cout << peek + 1 << '\n';
} else if (command == 4) {
if (peek == -1) {
cout << 1 << '\n';
} else {
cout << 0 << '\n';
}
} else {
if (peek == -1) {
cout << -1 << '\n';
} else {
cout << stack[peek] << '\n';
}
}
}
}
This post is licensed under CC BY 4.0 by the author.