10866 : 덱

네르기·2021년 9월 3일
0

알고리즘

목록 보기
41/76

어떤 문제인가?

덱 구현 문제.

내 코드

#include <stdio.h>
#include <string.h>
#define SIZE 10000

int D[SIZE], f = 0, r = SIZE-1, s = 0;

int main()
{
	int N, i;
	char c[12];
	scanf("%d", &N);
	for (i = 0; i < N; i++)
	{
		scanf("%s", c);
		if (strcmp(c, "push_front") == 0) {
		    f=(f-1+SIZE)%SIZE;
			scanf("%d",&D[f]);
			s++;
		}
		else if (strcmp(c, "push_back") == 0) {
			r=(r+1)%SIZE;
			scanf("%d", &D[r]);
			s++;
		}
		else if (strcmp(c, "pop_front") == 0) {
			printf("%d\n", s > 0 ? D[f] : -1);
			if(s>0) { s--; f=(f+1)%SIZE; }
		}
		else if (strcmp(c, "pop_back") == 0) {
			printf("%d\n", s > 0 ? D[r] : -1);
			if(s>0) { s--; r=(r-1+SIZE)%SIZE; }
	    }
		else if (strcmp(c, "size") == 0)
			printf("%d\n", s);
		else if (strcmp(c, "empty") == 0)
			printf("%d\n", s > 0 ? 0 : 1);
		else if (strcmp(c, "front") == 0)
			printf("%d\n", s > 0 ? D[f] : -1);
		else if (strcmp(c, "back") == 0)
			printf("%d\n", s > 0 ? D[r] : -1);
	}
}

큐와 똑같이, f와 r는 각각 양 끝을 향하도록 두자.

참고한 사이트들

  1. https://www.programiz.com/dsa/deque
  2. https://www.geeksforgeeks.org/implementation-deque-using-circular-array/amp/
profile
프로그래머와 애니메이터가 되고파

0개의 댓글