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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
namespace 연습장
{
internal class Program
{
static void Main(string[] args)
{
using var reader = new StreamReader(Console.OpenStandardInput());
using var print = new StreamWriter(Console.OpenStandardOutput());
_10845_boj boj = new _10845_boj();
boj.boj_10845();
}
}
internal class _10845_boj
{
public void boj_10845()
{
StringBuilder sb = new StringBuilder();
Queue queue = new Queue();
queue.n = int.Parse(Console.ReadLine());
queue.queue = new string[queue.n];
for (int i = 0; i < queue.n; i++)
{
string[] input = Console.ReadLine().Split();
switch(input[0])
{
case "push":
queue.Push(input[1]);
break;
case "pop":
sb.Append(queue.Pop() + "\n");
break;
case "size":
sb.Append(queue.size + "\n");
break;
case "empty":
sb.Append(queue.IsQueueEmpty() ? "1\n" : "0\n");
break;
case "front":
sb.Append(queue.Front() + "\n");
break;
case "back":
sb.Append(queue.Back() + "\n");
break;
}
}
if (sb.Length >= 1 && sb[sb.Length - 1] == '\n')
sb.Remove(sb.Length - 1, 1);
Console.WriteLine(sb);
}
}
public class Queue
{
public int n;
public int front = -1;
public int rear = -1;
public string[] queue;
public int size = 0;
public void Push(string data)
{
if (IsQueueFull())
return;
rear++;
queue[rear] = data;
size++;
}
public string Pop()
{
string res = "-1";
if (IsQueueEmpty())
return res;
front++;
res = queue[front];
queue[front] = null;
size--;
return res;
}
public bool IsQueueEmpty()
{
bool res = false;
if (rear == front)
res = true;
return res;
}
public bool IsQueueFull()
{
bool res = false;
if (rear == n - 1)
res = true;
return res;
}
public string Front()
{
string res = "-1";
if (IsQueueEmpty())
return res;
res = queue[front + 1];
return res;
}
public string Back()
{
string res = "-1";
if (IsQueueEmpty())
return res;
res = queue[rear];
return res;
}
}
}
|
cs |
출력값들을 StringBuilder형 변수에 넣고 출력하는 과정에서 마지막에 생기는 공백을 없애기 위한 코드인
if (sb[sb.Length - 1] == '\n')
이 코드가 sb의 길이가 0인 경우 (n번의 입력동안 push만 한 경우) indexOufOfRange 에러가 나는 실수를 했다.
'하루 한 접시' 카테고리의 다른 글
[백준] 6198번 : 옥상 정원 꾸미기 [C#] (0) | 2024.05.22 |
---|---|
[백준] 10799번 : 쇠막대기 [C#] (0) | 2024.05.21 |
[백준] 28279번: 덱 2 [C#] (0) | 2024.05.20 |
[백준] 2493번 : 탑 [C#] (0) | 2024.05.20 |
[백준] 1874번 : 스택 수열 [C#] (0) | 2024.05.16 |