18258: 큐 2
2022. 9. 24. 17:44ㆍC언어/백준
자료구조
실버 4
https://www.acmicpc.net/problem/18258
18258번: 큐 2
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
-결과
-코드
#include <stdio.h>
#include <string.h>
typedef struct Queue {
int data[2000000];
int front, rear;
} Queue;
void init(Queue *q) {
q->front = q->rear = -1;
}
int is_empty(Queue *q) {
return (q->front == q->rear);
}
int size(Queue *q) {
if (is_empty(q)) {
return 0;
}
return (q->rear - q->front);
}
void push(Queue *q, int data) {
q->data[++(q->rear)] = data;
}
int pop(Queue *q) {
if (is_empty(q)) return -1;
return q->data[++(q->front)];
}
int front(Queue *q) {
if (is_empty(q)) return -1;
return q->data[q->front + 1];
}
int back(Queue *q) {
if (is_empty(q)) return -1;
return q->data[q->rear];
}
int main(void) {
Queue q;
init(&q);
int N;
scanf("%d", &N);
while(N--) {
char str[6];
scanf("%s", str);
if (!strcmp(str, "push")) {
int data = 0;
scanf("%d", &data);
push(&q, data);
}
else if (!strcmp(str, "front")) {
printf("%d\n", front(&q));
}
else if (!strcmp(str, "back")) {
printf("%d\n", back(&q));
}
else if (!strcmp(str, "pop")) {
printf("%d\n", pop(&q));
}
else if (!strcmp(str, "size")) {
printf("%d\n", size(&q));
}
else if (!strcmp(str, "empty")) {
printf("%d\n", is_empty(&q));
}
}
return 0;
}
-풀이
이전에 풀었던 큐 문제처럼 큐를 구현하는 문제이다.
구조체로 큐를 선언하고 스택을 이용해서 풀어준다.
입력된 문자열에 해당하는 함수를 미리 선언하고, 그 입력값이 맞다면 함수를 실행하도록 작성한다.
입력된 문자열을 비교할때는 이전에 문제에서도 사용했던 strcmp를 사용하여 비교한다.
그리고 명령이 수행되면 값을 출력하도록 작성한다.
'C언어 > 백준' 카테고리의 다른 글
2675: 문자열 반복 (0) | 2022.09.24 |
---|---|
1764: 듣보잡 (0) | 2022.09.24 |
3052: 나머지 (0) | 2022.09.24 |
1158: 요세푸스 문제 (0) | 2022.09.24 |
10815: 숫자 카드 (0) | 2022.09.24 |