[BaekJoon] #10828 - 스택 [Java][C++]
[BaekJoon] #10828 - 스택 [Java][C++]
1. 아이디어
스택 자료구조를 구현하는 문제로 배열을 활용해서 구현했다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = 입력값 n)
3. 코드
풀이 [Java][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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.io.*;
import java.util.*;
public class Main {
static final int MAX = 10000;
static int[] stack = new int[MAX];
static int pos = 0;
static void push(int x) {
stack[pos++] = x;
}
static int pop() {
return stack[--pos];
}
static int size() {
return pos;
}
static boolean empty() {
return pos == 0;
}
static int top() {
return stack[pos - 1];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
while (n-- > 0) {
st = new StringTokenizer(br.readLine());
String q = st.nextToken();
if (q.equals("push")) {
int x = Integer.parseInt(st.nextToken());
push(x);
} else if (q.equals("pop")) {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(pop()).append("\n");
}
} else if (q.equals("size")) {
sb.append(size()).append("\n");
} else if (q.equals("empty")) {
if (empty()) {
sb.append("1\n");
} else {
sb.append("0\n");
}
} else {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(top()).append("\n");
}
}
}
System.out.println(sb);
}
}
pos는 스택에 새로 삽입할 수 있는 위치를 가리킨다.
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
const int MAX = 10000;
int st[MAX];
int pos = 0;
void push(int x) {
st[pos++] = x;
}
void pop() {
pos--;
}
int size() {
return pos;
}
bool empty() {
return pos == 0;
}
int top() {
return st[pos - 1];
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
while (n--) {
string q;
cin >> q;
if (q == "push") {
int x;
cin >> x;
push(x);
} else if (q == "pop") {
if (empty()) {
cout << -1 << '\n';
} else {
cout << top() << '\n';
pop();
}
} else if (q == "size") {
cout << size() << '\n';
} else if (q == "empty") {
cout << empty() << '\n';
} else {
if (empty()) {
cout << -1 << '\n';
} else {
cout << top() << '\n';
}
}
}
}
pos는 스택에 새로 삽입할 수 있는 위치를 가리킨다.
This post is licensed under CC BY 4.0 by the author.