안녕지구 #developer #bompapa

BOJ - 스택(10828)

|

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

구조체 배열

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

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

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

전체 코드

#include <cstring>
#include <stdio.h>

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

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

// 메인 함수
int main() {

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


	Node* head = '\0';
	char order[10];
	int count = 0;
	while (N--) {
		scanf("%s", order);

		if (order[1] == 'u') {
			int data;
			scanf("%d", &data);
			Node* node = allocNode();
			node->data = data;

			if (count == 0) {
				head = node;
			} else {
				node->next = head;
				head = node;
			}
			count++;
		} else if (order[0] == 'p') {
			if (head == '\0') {
				printf("%d\n", -1);
			} 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("%d\n", 1);
			} else {
				printf("%d\n", 0);
			}
		} else if (order[0] == 't') {
			if (count == 0) {
				printf("%d\n", -1);
			} else {
				printf("%d\n", head->data);
			}
		}
	};

	return 0;
}

Comments