꿈꾸는 새벽하늘

[자료구조] C언어로 스택(Stack) 구현하기 본문

⭐ Algorithm

[자료구조] C언어로 스택(Stack) 구현하기

rovemin 2022. 2. 16. 04:17

Stack ADT

push(item) : 스택이 full이 아닐 때 item을 스택에 삽입

pop() : 스택이 empty가 아닐 때 top의 item을 반환 후 제거

peek() : 스택이 empty가 아닐 때 top의 item을 반환 (*제거하지 않음) 

isFull() : 스택이 포화상태인지 확인

isEmpty() : 스택이 공백상태인지 확인

 

Source Code

// 배열을 이용한 스택을 전역 변수로 구현하는 방법

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

#define MAX_STACK_SIZE 100  // 스택의 최대 크기

typedef int element;            // 데이터의 자료형
element stack[MAX_STACK_SIZE];  // 1차원 배열
int top = -1;

// 스택이 비어 있는 상태인지 확인하는 함수
int isEmpty() {
    return (top == -1);
}

// 스택이 가득 찬 상태인지 확인하는 함수
int isFull() {
    return (top == (MAX_STACK_SIZE - 1));
}

// 삽입 함수
void push(element item) {
    if (isFull()) {
        printf("스택이 가득 찼습니다.\n");
        return;
    }
    else
        stack[++top] = item;
}

// 삭제 함수
element pop() {
    if (isEmpty()) {
        printf("스택이 비어 있습니다.\n");
        exit(1);    // 에러 발생 시 강제 종료
    }
    else
        return stack[top--];
}

// 피크 함수
element peek() {
    if (isEmpty()) {
        printf("스택이 비어 있습니다.\n");
        exit(1);    // 에러 발생 시 강제 종료
    }
    else
        return stack[top];
}


int main(void) {
    push(10);
    push(7);
    push(6);
    push(5);
    printf("%d\n", pop());
    printf("%d\n", peek());
    printf("%d\n", pop());
    printf("%d\n", pop());
    push(3);
    printf("%d\n", pop());

    return 0;
}
 

Output

'⭐ Algorithm' 카테고리의 다른 글

[자료구조] 스택(Stack)의 정의  (0) 2022.01.11