오늘은 백준 10828번 스택 문제를 풀어보겠습니다.
명령어 하나씩 어떻게 구현할지 설명해보겠습니다.
일단, 인덱스를 -1로 초기화한다.
-명령어가 push라면:
정수 하나를 입력받아서 배열의 (인덱스+1) 위치에 넣는다.
그 후, 배열의 인덱스를 하나 증가시킨다.
-명령어가 pop이라면:
만약 현재 인덱스가 0보다 작다면(증가되지 않고 처음 초기화한 상태 그대로라면) -1을 출력한다.
아니라면 배열에서 현재 인덱스 위치에 있는 값을 출력한다.
그 후, 배열에서 현재 인덱스 위치에 null 값을 넣고 인덱스를 하나 감소시킨다.
-명령어가 size라면:
현재 인덱스값에 1을 더한 값을 출력한다.
-명령어가 empty라면:
현재 인덱스가 0보다 작다면 배열이 비어있다는 의미이기 때문에 1을 출력한다.
아니라면 0을 출력한다.
-명령어가 top이라면:
만약 현재 인덱스가 0보다 작다면(증가되지 않고 처음 초기화한 상태 그대로라면) -1을 출력한다.
아니라면 배열에서 현재 인덱스 위치에 있는 값을 출력한다.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
int n;
char command[10];
int num = 0;
scanf("%d", &n);
int arr[10000];
int idx = -1;
for (int i = 0; i < n; i++) {
memset(command, 0, sizeof(command));
scanf("%s", command);
if (strcmp(command, "push") == 0) {
scanf("%d", &num); //명령어가 push일 때만 정수 입력받기
arr[idx + 1] = num;
idx++;
}
else if (strcmp(command, "top") == 0) {
if (idx < 0)
printf("-1\n");
else
printf("%d\n", arr[idx]);
}
else if (strcmp(command, "size") == 0) {
printf("%d\n", idx + 1);
}
else if (strcmp(command, "empty") == 0) {
if (idx < 0)
printf("1\n");
else
printf("0\n");
}
else if (strcmp(command, "pop") == 0) {
if (idx < 0)
printf("-1\n");
else {
printf("%d\n", arr[idx]);
arr[idx] = '\0';
idx--;
}
}
}
return 0;
}
[자료구조] 이진탐색트리(binary search tree) - AVL tree (0) | 2022.03.28 |
---|---|
[자료구조] 트리 탐색(tree traversal) 방법- inorder traverse, postorder traverse, preorder traverse, level order traversal (0) | 2022.03.18 |
[자료구조] linked list로 큐(queue) 구현하기 (0) | 2022.03.13 |
[자료구조] linked list로 스택(stack) 구현하기 (0) | 2022.03.13 |
[자료구조] 백준 10845번 큐 문제풀이 (0) | 2021.11.19 |
댓글 영역