[BaekJoon] #10845 - 큐 [Java][C++]
[BaekJoon] #10845 - 큐 [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
69
70
71
72
73
74
75
76
77
78
import java.io.*;
import java.util.*;
public class Main {
static final int MAX = 10000;
static int[] queue = new int[MAX];
static int front = 0, rear = 0;
static void push(int x) {
queue[rear++] = x;
}
static int pop() {
return queue[front++];
}
static int size() {
return rear - front;
}
static boolean empty() {
return front == rear;
}
static int front() {
return queue[front];
}
static int back() {
return queue[rear - 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 (q.equals("front")) {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(front()).append("\n");
}
} else {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(back()).append("\n");
}
}
}
System.out.println(sb);
}
}
front는 큐에서 꺼낼 원소의 위치를 가리키며, rear는 큐에 삽입할 빈 곳을 가리킨다.
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
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
const int MAX = 10000;
int q[MAX];
int s = 0, e = 0;
void push(int x) {
q[e++] = x;
}
void pop() {
s++;
}
int size() {
return e - s;
}
bool empty() {
return s == e;
}
int front() {
return q[s];
}
int back() {
return q[e - 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 << front() << '\n';
pop();
}
} else if (q == "size") {
cout << size() << '\n';
} else if (q == "empty") {
cout << empty() << '\n';
} else if (q == "front") {
if (empty()) {
cout << -1 << '\n';
} else {
cout << front() << '\n';
}
} else {
if (empty()) {
cout << -1 << '\n';
} else {
cout << back() << '\n';
}
}
}
}
s는 큐에서 꺼낼 원소의 위치를 가리키며, e는 큐에 삽입할 빈 곳을 가리킨다.
This post is licensed under CC BY 4.0 by the author.