[BaekJoon] 18258번 - 큐 2 [Java][C++]
[BaekJoon] 18258번 - 큐 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
47
48
49
50
51
52
53
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[] queue = new int[2000000];
int front = 0;
int rear = 0;
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
String command = st.nextToken();
if (command.equals("push")) {
int x = Integer.parseInt(st.nextToken());
queue[rear++] = x;
} else if (command.equals("pop")) {
if (front == rear) {
sb.append("-1\n");
} else {
sb.append(queue[front++]).append("\n");
}
} else if (command.equals("size")) {
sb.append(rear - front).append("\n");
} else if (command.equals("empty")) {
if (front == rear) {
sb.append("1\n");
} else {
sb.append("0\n");
}
} else if (command.equals("front")) {
if (front == rear) {
sb.append("-1\n");
} else {
sb.append(queue[front]).append("\n");
}
} else {
if (front == rear) {
sb.append("-1\n");
} else {
sb.append(queue[rear - 1]).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
45
46
47
48
49
50
51
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int queue[2000000];
int front = 0;
int rear = 0;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string command;
cin >> command;
if (command == "push") {
int x;
cin >> x;
queue[rear++] = x;
} else if (command == "pop") {
if (front == rear) {
cout << -1 << '\n';
} else {
cout << queue[front++] << '\n';
}
} else if (command == "size") {
cout << rear - front << '\n';
} else if (command == "empty") {
if (front == rear) {
cout << 1 << '\n';
} else {
cout << 0 << '\n';
}
} else if (command == "front") {
if (front == rear) {
cout << -1 << '\n';
} else {
cout << queue[front] << '\n';
}
} else {
if (front == rear) {
cout << -1 << '\n';
} else {
cout << queue[rear - 1] << '\n';
}
}
}
}
This post is licensed under CC BY 4.0 by the author.