[C] 스택(Stack) 배열형

2019. 7. 26. 19:16 기타/C언어

[C] 스택(Stack) 배열형


스택은 LIFO(Last In First Out) 구조이다.

스택은 배열로 나타낼 수 있으며, 동적 구현을 위해서 Linked List를 사용할 수도 있다.


배열로 구현할 경우, 제한된 배열 크기 안에서 스택을 사용할 수 있으며 Stack이 꽉찬 상태에서 push가 발생하면, Stack Overflow 처리를 그리고 스택이 비어있을 때 pop이 발생하면 Stack underflow 처리를 해줘야 한다.


스택에서는 현재 최상단의 위치를 가리키는 top 을 유지해야 한다.


#include <stdio.h>

#define MAX 10
int stack[MAX];        // 스택의 긴  통
int top;            // 스택의 상단

void init_stack(void){
    top = -1;
}

int push(int t){

    if (top >= MAX - 1){
        printf("\n    Stack overflow.");
        return -1;
    }

    stack[++top] = t;
    return t;
}

int pop(void){
    if (top < 0){
        printf("\n   Stack underflow.");
        return -1;
    }
    return stack[top--];
}

void print_stack(void){
    int i;
    printf("\n Stack contents : TOP ----> Bottom\n");
    for (i = top; i >= 0; i--){
        printf("%-6d", stack[i]);
    }
}

void main(void){

    int i;
    init_stack();

    printf("\nPush 5,4,7,8,2,1");
    push(5);
    push(4);
    push(7);
    push(8);
    push(2);
    push(1);
    print_stack();

    printf("\nPop");
    i = pop();
    print_stack();
    printf("\n   popping value is %d", i);

    printf("\nPush 3, 2, 5, 7, 2");
    push(3);
    push(2);
    push(5);
    push(7);
    push(2);
    print_stack();

    printf("\nNow stack is full, push 3");
    push(3);        // 스택 오버플로우
    print_stack();

    printf("\nInitialize stack");
    init_stack();
    print_stack();

    printf("\nNow stack is empty, pop");
    i = pop();
    print_stack();
    printf("\n    popping value is %d", i);

    return 0;
}



출처: https://hyeonstorage.tistory.com/345?category=622873 [개발이 하고 싶어요]