728x90
728x90
https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
스택을 구현하는 문제다
스택이란, 먼저 들어간 것이 나중에 나오는 후입선출(LIFO, Last In First Out) 방식의 자료구조이다
예를 들어,
1, 2, 3을 순서대로 넣고 뺀다고 하면
빠지는 순서는 3, 2, 1이 된다
(구현)
나는 명령어 중 push X는
push를 먼저 문자열로 받고
X는 따로 data라는 int형 변수로 입력받았다
명령어는 command라는 문자열로 입력받았는데
push, pop, size, empty, top 각 단어의 최대 길이는 5에
끝에 NULL 문자를 포함하여
6칸짜리 문자열로 해주었다
(코드)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#define TRUE 1
#define FALSE 0
#define ERROR -1
#define STACK_LEN 10000
typedef struct _Stack {
int arr[STACK_LEN];
int topIndex;
} Stack;
void push(Stack*, int);
int pop(Stack*);
int size(Stack*);
int empty(Stack*);
int top(Stack*);
int main() {
int N, data; // N: 명령어 개수, data: 명령어 중 'push X'에서의 X
Stack stack;
stack.topIndex = -1; // stack에 들어가 있는 게 아무 것도 없으니 topIndex를 -1으로 초기화
scanf("%d", &N);
/* 명령어 단어 'push', 'pop', 'size', 'empty', 'top'의 최대 길이는 6이므로 (끝에 NULL문자 포함) */
char command[6];
for (int i = 0; i < N; i++) {
scanf("%s", command);
/* 입력이 'push X'일 때는 'push'와 'X'를 구분하여 받음 */
if (!strcmp(command, "push")) { // 입력이 'push'일 때
scanf("%d", &data); // X까지 받아줌
push(&stack, data);
}
else if (!strcmp(command, "pop")) // 입력이 'pop'일 때
printf("%d\n", pop(&stack));
else if (!strcmp(command, "size")) // 입력이 'size'일 때
printf("%d\n", size(&stack));
else if (!strcmp(command, "empty")) // 입력이 'empty'일 때
printf("%d\n", empty(&stack));
else if (!strcmp(command, "top")) // 입력이 'top'일 때
printf("%d\n", top(&stack));
}
return 0;
}
void push(Stack* pstack, int data) {
(pstack->topIndex)++;
pstack->arr[pstack->topIndex] = data;
}
int pop(Stack* pstack) {
if (pstack->topIndex == -1)
return ERROR;
else {
int data = pstack->arr[pstack->topIndex];
pstack->topIndex--;
return data;
}
}
int size(Stack* pstack) {
return (pstack->topIndex + 1);
}
int empty(Stack* pstack) {
if (pstack->topIndex == -1)
return TRUE;
else
return FALSE;
}
int top(Stack* pstack) {
if (pstack->topIndex == -1)
return ERROR;
else
return(pstack->arr[pstack->topIndex]);
}
난이도: solved.ac 실버 4
반응형