array_stack.c

Download
c 124 lines 2.6 KB
  1// array_stack.c
  2// λ°°μ—΄ 기반 μŠ€νƒ κ΅¬ν˜„
  3// LIFO (Last In, First Out) 자료ꡬ쑰
  4
  5#include <stdio.h>
  6#include <stdlib.h>
  7#include <stdbool.h>
  8
  9#define MAX_SIZE 100
 10
 11typedef struct {
 12    int data[MAX_SIZE];
 13    int top;
 14} Stack;
 15
 16// μŠ€νƒ μ΄ˆκΈ°ν™”
 17void stack_init(Stack *s) {
 18    s->top = -1;
 19}
 20
 21// λΉ„μ–΄μžˆλŠ”μ§€ 확인
 22bool stack_isEmpty(Stack *s) {
 23    return s->top == -1;
 24}
 25
 26// 가득 μ°ΌλŠ”μ§€ 확인
 27bool stack_isFull(Stack *s) {
 28    return s->top == MAX_SIZE - 1;
 29}
 30
 31// Push - 맨 μœ„μ— μš”μ†Œ μΆ”κ°€ (O(1))
 32bool stack_push(Stack *s, int value) {
 33    if (stack_isFull(s)) {
 34        printf("Stack Overflow!\n");
 35        return false;
 36    }
 37    s->data[++s->top] = value;
 38    return true;
 39}
 40
 41// Pop - 맨 μœ„ μš”μ†Œ 제거 ν›„ λ°˜ν™˜ (O(1))
 42bool stack_pop(Stack *s, int *value) {
 43    if (stack_isEmpty(s)) {
 44        printf("Stack Underflow!\n");
 45        return false;
 46    }
 47    *value = s->data[s->top--];
 48    return true;
 49}
 50
 51// Peek - 맨 μœ„ μš”μ†Œ 확인 (제거 μ•ˆν•¨) (O(1))
 52bool stack_peek(Stack *s, int *value) {
 53    if (stack_isEmpty(s)) {
 54        return false;
 55    }
 56    *value = s->data[s->top];
 57    return true;
 58}
 59
 60// μŠ€νƒ 좜λ ₯ (λ””λ²„κΉ…μš©)
 61void stack_print(Stack *s) {
 62    printf("Stack (top=%d): ", s->top);
 63    for (int i = 0; i <= s->top; i++) {
 64        printf("%d ", s->data[i]);
 65    }
 66    printf("\n");
 67}
 68
 69// μŠ€νƒ 크기 λ°˜ν™˜
 70int stack_size(Stack *s) {
 71    return s->top + 1;
 72}
 73
 74// ν…ŒμŠ€νŠΈ μ½”λ“œ
 75int main(void) {
 76    Stack s;
 77    stack_init(&s);
 78
 79    printf("=== λ°°μ—΄ 기반 μŠ€νƒ ν…ŒμŠ€νŠΈ ===\n\n");
 80
 81    // Push ν…ŒμŠ€νŠΈ
 82    printf("[ Push μ—°μ‚° ]\n");
 83    for (int i = 1; i <= 5; i++) {
 84        printf("Push %d -> ", i * 10);
 85        stack_push(&s, i * 10);
 86        stack_print(&s);
 87    }
 88
 89    // Peek ν…ŒμŠ€νŠΈ
 90    printf("\n[ Peek μ—°μ‚° ]\n");
 91    int top;
 92    if (stack_peek(&s, &top)) {
 93        printf("Top κ°’: %d (μŠ€νƒμ€ λ³€κ²½ μ•ˆλ¨)\n", top);
 94        stack_print(&s);
 95    }
 96
 97    // Pop ν…ŒμŠ€νŠΈ
 98    printf("\n[ Pop μ—°μ‚° ]\n");
 99    int value;
100    while (stack_pop(&s, &value)) {
101        printf("Popped: %d, ", value);
102        stack_print(&s);
103    }
104
105    // Underflow ν…ŒμŠ€νŠΈ
106    printf("\n[ Underflow ν…ŒμŠ€νŠΈ ]\n");
107    printf("빈 μŠ€νƒμ—μ„œ Pop μ‹œλ„: ");
108    stack_pop(&s, &value);
109
110    // Overflow ν…ŒμŠ€νŠΈ
111    printf("\n[ Overflow ν…ŒμŠ€νŠΈ ]\n");
112    Stack s2;
113    stack_init(&s2);
114    printf("MAX_SIZEλ₯Ό μ΄ˆκ³Όν•˜λŠ” Push μ‹œλ„...\n");
115    for (int i = 0; i <= MAX_SIZE; i++) {
116        if (!stack_push(&s2, i)) {
117            printf("총 %d개 μš”μ†Œ μ‚½μž… ν›„ Overflow λ°œμƒ\n", i);
118            break;
119        }
120    }
121
122    return 0;
123}