5_BAEKJOON

5 BAEKJOON) 백준 10828 : 스택

Mi:sAng 2022. 11. 7. 20:34

*스택의 핵심은 top을 기록하는 것이다. top만 알고 있으면 다른 함수를 구현하는 것은 어렵지 않다.

 

* 문자열을 받는 과정에서 기억이 가물가물해서 시간이 좀... 걸렸다.   %[^\n]을 이용하면 개행까지의 문자열을 읽을 수 있다. 즉 공백도 포함가능하다는 것이다.  하지만 이 문제에서는 쓸일이 없었다... 

 

*내가 겪은 오류 : Run-Time Check Failure #2 - Stack around the variable 'order' was corrupted

order 배열에서 크기가 작아서 오류가 생겼던 것이었다. 

 

*P.S. 내일도 한 문제 풀려나..?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main() {
	int stack[10000] = { 0, };
	int val = 0;
	scanf(" %d", &val);
	char order[10] = "";
	int top = -1;
	
	for (int i = 0; i < val; i++) {
		scanf(" %s", order);
		if (strcmp(order, "push") == 0) {
			int value = 0;
			if (top == -1) {

				scanf(" %d", &value);
				top++;
				stack[top] = value;

			}
			else {
				scanf(" %d", &value);
				top++;
				stack[top] = value;

			}

			order[0] = '\0';
		}
		else if (strcmp(order, "top") == 0) {
			if (top == -1) {
				printf("%d\n", top);
			}
			else {
				printf("%d\n", stack[top]);
			}
			order[0] = '\0';
		}
		else if (strcmp(order, "size") == 0) {
			printf("%d\n", top + 1);
			order[0] = '\0';
		}
		else if (strcmp(order, "empty") == 0) {
			if (top == -1) {
				printf("%d\n",1);
			}
			else {
				printf("%d\n",0);
			}
			order[0] = '\0';
		}
		else if (strcmp(order, "pop") == 0) {
			if (top == -1) {
				printf("%d\n",top);
			}
			else {
				printf("%d\n", stack[top]);
				stack[top] = -1;
				top--;

			}
			order[0] = '\0';
		}

	}


	return 0;
}