안녕지구 #developer #bompapa

BOJ - 큐(10845)

|

스택(10828)과 마찬가지로 간단한 링크드 리스트를 이용해서 구현한 입니다. 배열을 사용해서 더 간단하게도 구현 가능하지만 구조체 배열을 연습하고자 링크드 리스트를 사용했습니다.

구조체 배열

// 정적이지만 동적할당처럼 사용하는 구조체 배열
typedef struct node {
	int data;
	node* next;
} Node;

int nodeIndex = 0;
Node nodeArray[10000];
Node* allocNode() {
	return &nodeArray[nodeIndex++];
};

// 아래와 같이 사용할 수 있습니다.
Node* node = allocNode();

전체 코드

#include <stdio.h>

// 구조체 배열
typedef struct node {
	int data;
	node* next;
} Node;

int nodeidx = 0;
Node nodearray[10000];
Node* allocNode() {
	return &nodearray[nodeidx++];
};

// 메인 함수
int main() {

	int N;
	scanf("%d", &N);

	Node* head = '\0';
	Node* tail = '\0';

	char order[6];
	int count = 0;
	while (N--) {
		scanf("%s", order);

		// 새로운 노드 생성해서 큐에 PUSH
		if (order[1] == 'u') {
			int data;
			scanf("%d", &data);
			Node* node = allocNode();
			node->data = data;
			if (count == 0) {
				head = node;
				tail = node;
			} else {
				tail->next = node;
				tail = node;
			}
			count++;

		// 상위 노드(head) POP
		} else if (order[0] == 'p') {
			if (count == 0) printf("-1\n");
			else {
				printf("%d\n", head->data);
				head = head->next;
				count--;
			}

		// 큐에 있는 노드 갯수 출력
		} else if (order[0] == 's') {
			printf("%d\n", count);

		// 큐가 비어 있는지 확인
		} else if (order[0] == 'e') {
			if (count == 0) printf("1\n");
			else printf("0\n");

		// 상위 노드(head) 값 출력
		} else if (order[0] == 'f') {
			if (count == 0) printf("-1\n");
			else {
				printf("%d\n", head->data);
			}

		// 마지막 노드(tail) 값 출력
		} else if (order[0] == 'b') {
			if (count == 0) printf("-1\n");
			else {
				printf("%d\n", tail->data);
			}
		}
	};
	return 0;
}

Comments