지식보부상님의 공부 일지

백준 10845번: 큐 본문

C언어 문제풀이

백준 10845번: 큐

지식보부상님 2023. 4. 21. 13:32

https://www.acmicpc.net/problem/10845

 

10845번: 큐

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

큐를 구현하는 문제였습니다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(){
	int N = 0;
	int front = -1, back = -1;
	int queue[10001];
	char str[11], *ptr;

	//명령의 개수
	scanf("%d", &N);

	for (int i = 0; i < N; i++) {
		//명령 (엔터 전까지 받는다.)
		scanf(" %[^\n]s", &str);

		//push 명령
		if (!strncmp(str, "push", 4)) {
			//push 뒤의 주어진 수를 int로 바꾸는 과정
			ptr = strtok(str, " ");
			ptr = strtok(NULL, " ");
			queue[++back] = atoi(ptr);
		}

		//pop 명령
		else if (!strncmp(str, "pop", 3)) {
			if (front == back)
				printf("-1\n");
			else {
				printf("%d\n", queue[++front]);
				queue[front] = 0;
			}
		}

		//size 명령
		else if (!strncmp(str, "size", 4)) 
			printf("%d\n", back - front);

		//empty 명령
		else if (!strncmp(str, "empty", 5)) {
			if (front == back)	printf("1\n");
			else
				printf("0\n");
		}

		//front 명령
		else if(!strncmp(str, "front", 5)){
			if (front == back)	printf("-1\n");
			else
				printf("%d\n", queue[front + 1]);
		}

		//back 명령
		else {
			if (front == back)	printf("-1\n");
			else
				printf("%d\n", queue[back]);
		}
	}
	return 0;
}

'C언어 문제풀이' 카테고리의 다른 글

SWEA 2001번: 파리 퇴치  (2) 2023.11.06
SWEA 1961번: 숫자 배열 회전  (1) 2023.11.06
백준 10773번: 제로  (0) 2023.04.21
백준 10828번: 스택  (2) 2023.04.20
백준 9012번: 괄호  (0) 2023.04.20