<aside> 🔥 한쪽 끝에서만 데이터를 넣고 빼는 후입선출 자료구조

</aside>

스택은 기본적으로 후입선출 구조로 이루어져 있다

300px-Data_stack.svg.png

스택의 사용 예제

스택 구조

#include <stdio.h>
#include <stdlib.h>

#define STACK_SIZE 10 //스택 사이즈

int stack[STACK_SIZE]; // 스택 초기화
int top = -1; //가장 위의 원소를 가르킬 top 변수

int isFull(){ //스택 오버플로우 방지
    if(top >= STACK_SIZE -1){    // stack의 인덱스 0부터 시작
        printf("Error : Stack is Full!\\n");
        return 1;
    }
    return 0;
}
int isEmpty(){ //스택 언더플로우 방지
    if(top == -1){
        printf("Error : Stack is empty!\\n");
        return 1;
    }
    return 0;
}
void push(int data){ //스택 값 넣기
    if(!isFull()){
        top++;
        stack[top] = data;
    }
}
int pop(){ //스택 값 빼기
    if(!isEmpty()){
        return stack[top--];
    }
}

void printStack(){ //모든 스택 출력 *아래부터 위로 출력해야 됨*
    int i;
    for(i=0; i<=top; i++){
        printf("%d ", stack[i]);
    }
    printf("\\n");
}

메모리 스택

정적 메모리 할당에 사용되며 후입선출이다.