C_C++

(C언어) 스택에 삽입 삭제하는 프로그램 소스

고니자니 2023. 5. 17. 20:55
반응형

다음 코드는 스택에 삽입과 삭제를 하는 C언어 소스 코드입니다.

테스트를 위해서 스택의 크기는 #define으로 3으로 설정했습니다.

#include <stdio.h>
#define MAX_SIZE 3

// Stack structure
typedef struct {
    int data[MAX_SIZE];
    int top;
} Stack;

// Initialize stack
void init(Stack* stack) {
    stack->top = -1;
}

// Check if the stack is empty
int isEmpty(Stack* stack) {
    return stack->top == -1;
}

// Check if the stack is full
int isFull(Stack* stack) {
    return stack->top == MAX_SIZE - 1;
}

// Insert an element into the stack (push operation)
void push(Stack* stack, int value) {
    if (isFull(stack)) {
        printf("Stack overflow! Cannot push element.\n");
        return;
    }

    stack->top++;
    stack->data[stack->top] = value;
}

// Delete an element from the stack (pop operation)
int pop(Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack underflow! Cannot pop element.\n");
        return -1;
    }

    int value = stack->data[stack->top];
    stack->top--;
    return value;
}

int main() {
    Stack stack;
    init(&stack);

    // Pushing elements onto the stack
    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);
    push(&stack, 40);

    // Popping elements from the stack
    for (int i = 0; i < 4; i++)
    {
        int poppedElement = pop(&stack);
        printf("Popped element: %d\n", poppedElement);
    }

    return 0;
}

 

728x90
반응형