자료구조
C언어 스택 PUSH, POP 과정
by sleepycho
2024. 4. 23.
#include <stdio.h>
#include <stdbool.h>
#define MAX_STACK_SIZE 100
int stack[MAX_STACK_SIZE];
int top = -1;
int IsEmpty();
int IsFull();
void push(int value);
int pop();
int main() {
push(3);
push(5);
push(12);
printf("%d ", pop());
printf("%d ", pop());
printf("%d ", pop());
return 0;
}
int IsEmpty() { // 스택이 비어있는지 확인
if (top < 0) {
return true;
} else {
return false;
}
}
int IsFull() { // 스택이 가득 찼는지 확인
if (top >= MAX_STACK_SIZE - 1) {
return true;
} else {
return false;
}
}
void push(int value) {
if (IsFull() == true) {
printf("스택이 가득 찼습니다."); // 스택이 가득 찼다면 오버플로로 인식하고 종료
} else {
stack[++top] = value; // 스택이 가득 차지 차있지 않다면 top을 증가시키고
// top이 가리키는 스택 위치에 데이터 추가
}
}
int pop() {
if (IsEmpty() == true) {
printf("스택이 비었습니다."); // 스택이 비어있으면 언더플로우로 인식하고 종료
} else {
return stack[top--]; // 비어있지 않으면 top을 가리키는 데이터 제거
// top 감소 및 성공 반환 (삭제한 값 반환)
}
}