SHyeonL / Future_Internet_LAB_Algorithm

미래 인터넷 연구실 알고리즘 스터디
0 stars 0 forks source link

10828 (스택) #6

Closed rhkrdkdms123 closed 1 year ago

rhkrdkdms123 commented 1 year ago
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STACK_SIZE 10000

typedef int element;

typedef struct {
    element data[MAX_STACK_SIZE];
    int top;
} StackType;

void init_stack(StackType* s) {
    s->top = -1; //스택이 공백상태면 top은 -1
}

int is_empty(StackType* s) {
    return (s->top == -1);
}

int is_full(StackType* s) {
    return (s->top == (MAX_STACK_SIZE - 1));
}

void push(StackType* s, element item) {
    if (is_full(s)) {
        fprintf(stderr, "스택 포화 에러\n");
        return;
    }
    else s->data[++(s->top)] = item;
}

element pop(StackType* s) {
    if (is_empty(&s)) {
        fprintf(stderr, "스택 공백 에러\n");
        exit(1);
    }
    else return s->data[(s->top)--];
}

int main(void) {
    int count;
    char cmd[20];
    int num;

    StackType s;
    init_stack(&s);

    scanf("%d", &count);
    getchar();

    for (int i = 0; i < count; i++) {
        scanf("%s", cmd);
        //명령어 구별
        if (!strcmp(cmd, "push")) {
            scanf("%d", &num);
            push(&s, num);
        }
        else if (!strcmp(cmd, "pop")) {
            printf("%d\n", is_empty(&s) ? -1 : pop(&s));
        }
        else if (!strcmp(cmd, "size")) {
            printf("%d\n", s.top + 1);
        }
        else if (!strcmp(cmd, "empty")) {
            printf("%d\n", is_empty(&s));
        }
        else if (!strcmp(cmd, "top")) {
            printf("%d\n", is_empty(&s) ? -1 : s.data[s.top]);
        }
    }

    return 0;
}