본문 바로가기
백준/C

백준 10828번 : 스택 [C]

by 대니스 2022. 8. 17.

주소 : https://www.acmicpc.net/problem/10828

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

소스 코드 :

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE_STACK 10001

typedef int element;
typedef struct{
	int top;
	element data[MAX_SIZE_STACK];
}StackType;

init_stack(StackType* s)
{
	s->top = -1;
}

int is_empty(StackType* s)
{
	if (s->top == -1)
		return 1;
	else return 0;
}

int is_full(StackType* s)
{
	if (s->top == MAX_SIZE_STACK - 1)
		return 1;
	else return 0;
}

void push(StackType *s, element item)
{
	if (is_full(s))
	{
		printf("-1");
		return;
	}
	else s->data[++(s->top)] = item;
}

element pop(StackType* s)
{
	if (is_empty(s))
	{
		return;
	}
	else return s->data[(s->top)--];
}

element peek(StackType* s)
{
	if (is_empty(s))
	{
		return;
	}
	else return s->data[s->top];
}
int main()
{
	int n = 0;
	char order[20];
	int num = 0;
	StackType s;
	init_stack(&s);
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
	{
		scanf("%s", &order);
		if (strcmp(order, "push")==0)
		{
			scanf("%d", &num);
			push(&s, num);
		}
		
		else if (strcmp(order, "pop") == 0)
		{
			if (is_empty(&s))
				printf("-1\n");
			else printf("%d\n", pop(&s));
		}
		
		else if (strcmp(order, "size") == 0)
		{
			if (s.top >= 0)
				printf("%d\n", (s.top) + 1);
			else printf("0\n");
		}
		
		else if (strcmp(order, "empty") == 0)
		{
			if (is_empty(&s))
			{
				printf("1\n");
			}
			else printf("0\n");
		}

		else if (strcmp(order, "top") == 0)
		{
			if (is_empty(&s))
				printf("-1\n");
			else printf("%d\n", peek(&s));
		}
	}
	return 0;
}

마무리 : 이 문제는 스택의 기본 문제로스택을 push하거나 pop하는 등등 문제에 조건에 맞게 행하면 출력을 하는 문제로 스택만 잘 안다면 어렵지 않은 문제이다.

'백준 > C' 카테고리의 다른 글

백준 10845번 : 큐 [C]  (0) 2022.08.18
백준 10773번 : 제로 [C]  (0) 2022.08.17
백준 2164번 : 카드2 [C]  (0) 2022.08.11
백준 1259번 : 팰린드롬수 [C]  (0) 2022.08.04
백준 15829번 : Hashing [C]  (0) 2022.08.03