////////
Search
Duplicate

Stack

Created
2021/03/20 18:22
Tags

Summary

Stack은 LIFO (Last In First Out)

Description

스택의 사전적 의미는 '차곡 차곡 쌓여진 더미' 입니다.
스택은 한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 구조로 되어있습니다. 자료를 넣는 것을 '밀어넣는다' 하여 PUSH 라고 하고, 반대로 넣어놓은 자료를 꺼내는 것을 POP이라 합니다. 먼저 들어온 것이 나중에 나간다 하여 LIFO (Last In First Out)라고 합니다.
사진 출처

Problem Solving

#include<iostream> #include<string> typedef struct stack_s { int a[10000] = { 0, }; int topIndex; }stack; int k[10000] = { 0, }; int k_cnt = 0; int String_to_int(std::string M) { if (!(M.compare("top")))return 0; if (!(M.compare("size")))return 1; if (!(M.compare("pop")))return 2; if (!(M.compare("empty")))return 3; } void push(stack * Stack, int data) { Stack->topIndex++; Stack->a[Stack->topIndex] = data; } void top(stack * Stack) { if (Stack->topIndex < 0) { k[k_cnt]= -1; k_cnt++; } else { k[k_cnt]= Stack->a[Stack->topIndex]; k_cnt++; } } void size(stack * Stack) { k[k_cnt]= Stack->topIndex + 1; k_cnt++; } void pop(stack * Stack) { if (Stack->topIndex < 0) { k[k_cnt]= -1; k_cnt++; } else { k[k_cnt]= Stack->a[Stack->topIndex]; k_cnt++; Stack->topIndex--; } } void empty(stack * Stack) { if (Stack->topIndex < 0) { k[k_cnt]= 1; k_cnt++; } else { k[k_cnt]= 0; k_cnt++; } } void ElseCase(stack * Stack, std::string M) { switch (String_to_int(M)) { case 0:top(Stack); break; case 1:size(Stack); break; case 2:pop(Stack); break; case 3:empty(Stack); break; } } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int N, M_p; std::string M; stack Stack; Stack.topIndex = -1; std::cin >> N; for (int i = 0; i < N; i++) { std::cin >> M; if (!(M.compare("push"))) { // 입력 값이 push이면 std::cin >> M_p; push(&Stack, M_p); } else { ElseCase(&Stack,M); } } for (int i = 0; i < k_cnt; i++) { std::cout << k[i] << std::endl; } return 0; }
C++
복사