자료구조
스택 코드와 PUSH, POP 과정 (학교 과제, p56)
치즈샌드CS
2024. 4. 16. 11:55
#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(){ // (POP 1)스택이 비어있는지 확인
if(top < 0){
return true;
}else{
return false;
}
}
int IsFull(){ // (PUSH 1)스택이 가득 찼는지 확인
if(top >= MAX_STACK_SIZE - 1){
return true;
}else{
return false;
}
}
void push(int value){
if(IsFull() == true){
printf("스택이 가득 찼습니다."); // (PUSH 2)스택이 가득 찼다면 오버플로로우로 인식하고 종료
}else{
stack[++top] = value; // (PUSH 3)스택이 가득 차지 차있지 않다면 top을 증가 시키고
// (PUSH 4)top이 가리키는 스택 위치에 데이터 추가
}
}
int pop(){
if(IsEmpty() == true){
printf("스택이 비었습니다."); // (POP 2)스택이 비어있으면 언더플로우로 인식하고 종료
}else{
return stack[top--]; // (POP 3)비어있지 않으면 top을 가리키는 데이터 제거
// (POP 4)top 감소 및 (POP 5)성공 반환(삭제한 값 반환)
}
}