![[BOJ] 백준_10845번_큐](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FbyPQcQ%2FbtrdqRQMkIA%2FSMKIHRGAfdA5FWsGZJY7OK%2Fimg.png)
[BOJ] 백준_10845번_큐백준 알고리즘2021. 8. 26. 18:00
목차
문제 출처
https://www.acmicpc.net/problem/10845
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
코드
//[BOJ] 10845 Queue
#include <stdio.h>
#include <stdlib.h>
#define EMPTY 0
typedef struct node {
int data;
struct node* link;
}Queue;
Queue* GetNode()
{
Queue* tmp;
tmp = (Queue*)malloc(sizeof(Queue));
tmp->link = EMPTY;
return tmp;
}
void Push(Queue** front, Queue** rear, int data)
{
if (*front == EMPTY)
{
*front = GetNode();
*rear = *front;
}
else
{
(*rear)->link = GetNode();
*rear = (*rear)->link;
}
(*rear)->data = data;
}
int Pop(Queue** front, Queue** rear)
{
Queue* tmp;
int data;
if (*front == EMPTY)
{
return -1;
}
else
{
tmp = *front;
data = tmp->data;
*front = tmp->link;
free(tmp);
return data;
}
}
int Empty(Queue** front)
{
if (*front == EMPTY)
return 1;
else
return 0;
}
int main()
{
Queue* front = EMPTY;
Queue* rear = EMPTY;
char str[20];
int size = 0;
int input_int, N, n=0;
scanf("%d", &N);
while (n < N)
{
scanf("%s", str);
if (!strcmp(str, "push"))
{
size++;
scanf("%d", &input_int);
Push(&front, &rear, input_int);
}
else if (!strcmp(str, "pop"))
{
size--;
if (size < 0)
size = 0;
printf("%d\n", Pop(&front, &rear));
}
else if (!strcmp(str, "empty"))
{
printf("%d\n", Empty(&front));
}
else if (!strcmp(str, "size"))
{
printf("%d\n", size);
}
else if (!strcmp(str, "front"))
{
if (Empty(&front) == 1)
printf("-1\n");
printf("%d\n", front->data);
}
else if (!strcmp(str, "back"))
{
if (Empty(&front) == 1)
printf("-1\n");
printf("%d\n", rear->data);
}
n++;
}
return 0;
}
실행과 종료는 정상적으로 잘 되지만 런타임 에러 판정을 받았다. 배열이나 이런 것보다 연결리스트가 더 익숙해서 이렇게 해봤는데 배열로 해결하는 방법을 찾아봐야겠다. pop 입력 시 단순히 size를 1 빼는 식으로 작성하다 보니 데이터가 없을 시 pop을 입력받으면 size가 음수가 되어버리는 문제가 있었다. 그래서 음수로 넘어가는 것을 방지하기 위해 if (size < 0) size = 0; 코드를 추가했다.
728x90
반응형
'백준 알고리즘' 카테고리의 다른 글
[BOJ] 백준_10809번_알파벳 찾기 / C언어 (0) | 2021.09.02 |
---|---|
[BOJ] 백준_1934번_최소공배수 / C언어 (0) | 2021.09.01 |
[BOJ] 백준_10430번_나머지 (0) | 2021.09.01 |
[BOJ] 백준_2609번_최대공약수와 최소공배수 (0) | 2021.08.31 |
[BOJ] 백준_9012번_괄호 (0) | 2021.08.30 |
@kdj :: Childev'note
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!