[C언어] 백준 10828 : 스택

mainsain·2022년 3월 30일
0

백준

목록 보기
58/64

흐름

스택이다. 피신때나 피신 이후에나 듣기는 많이 들었다. 스택이라는 공간에 abc순서대로 들어가면, 나올때는 cba로 나온다. 재귀할때 설명을 많이 들었었다.
이번엔 그 스택을 우리가 구현해보는 것이다. 문제를 보면, 총 5가지의 명령어가 있고, 우리는 그걸 이용할 것이다.

코드

#include <stdio.h>
#include <string.h>
#define stack_size 10001

int high = -1;
int stack[stack_size];

void push(int x)
{
	high++;
	stack[high] = x;
}
int empty()
{
	if (high == -1)
		return 1;
	else
		return 0;
}
int pop()
{
	if (empty())
	{
		return -1;
	}
	else
	{
		return stack[high--];
	}
}
int top()
{
	if (empty())
		return -1;
	else
		return stack[high];
}
int main()
{

	int N = 0, push_data = 0;
	char command[5] = {0, };

	scanf("%d", &N);

	for (int i = 0; i < N; i++)
	{

		scanf("%s", command);

		if (!strcmp(command, "push"))
		{
			scanf("%d", &push_data);
			push(push_data);
		}
		else if (!strcmp(command, "pop"))
		{
			printf("%d\n", pop());
		}
		else if (!strcmp(command, "empty"))
		{
			printf("%d\n", empty());
		}
		else if (!strcmp(command, "size"))
		{
			printf("%d\n", high + 1);
		}
		else if (!strcmp(command, "top"))
		{
			printf("%d\n", top());
		}
	}

	return 0;
}

코드는 정말 쉽다.
https://code-lab1.tistory.com/5 여기에서 이론을 배웠고,
https://mu7a7ion.tistory.com/25 여기에서 적용을 배웠다.

근데 더 찾아보니, 연결 리스트로 푸는 방법이 있다고 한다.
곧 피신을 하기에, 연결리스트로 푸는 방법을 익혀두면 좋을 것 같아 공부하기로 했다.

먼저 골드를 찍고, 수정을 할 것이다.

연결 리스트

profile
새로운 자극을 주세요.

0개의 댓글