💯🌊자료구조&알고리즘/C언어

스택 자료구조 c언어

들판속초록풀 2025. 4. 21. 11:01

 

연결리스트로 구현한 c언어

 

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

// 노드 구조체 정의
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 스택 구조체 정의
typedef struct Stack {
    Node* top;
} Stack;

// 스택 초기화
void init(Stack* s) {
    s->top = NULL;
}

// 스택이 비었는지 확인
int isEmpty(Stack* s) {
    return s->top == NULL;
}

// push: 스택에 데이터 삽입
void push(Stack* s, int value) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (!newNode) {
        printf("메모리 할당 실패!\n");
        return;
    }
    newNode->data = value;
    newNode->next = s->top;
    s->top = newNode;
}

// pop: 스택에서 데이터 꺼내기
int pop(Stack* s) {
    if (isEmpty(s)) {
        printf("스택이 비어있습니다!\n");
        return -1;
    }

    Node* temp = s->top;
    int value = temp->data;
    s->top = temp->next;
    free(temp);

    return value;
}

// peek: 맨 위 값 확인 (삭제 안함)
int peek(Stack* s) {
    if (isEmpty(s)) {
        printf("스택이 비어있습니다!\n");
        return -1;
    }

    return s->top->data;
}

// 스택 전체 메모리 해제
void clear(Stack* s) {
    while (!isEmpty(s)) {
        pop(s);
    }
}

// 테스트용 main 함수
int main() {
    Stack s;
    init(&s);

    push(&s, 10);
    push(&s, 20);
    push(&s, 30);

    printf("Top: %d\n", peek(&s)); // 30
    printf("Pop: %d\n", pop(&s));  // 30
    printf("Pop: %d\n", pop(&s));  // 20
    printf("Pop: %d\n", pop(&s));  // 10
    printf("Pop: %d\n", pop(&s));  // 스택이 비어있습니다!

    clear(&s); // 메모리 정리

    return 0;
}

 

 

배열을 이용한 스택 자료구조

 

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

#define MAX_SIZE 100

// 스택 구조 정의
typedef struct {
    int data[MAX_SIZE];
    int top;
} Stack;

// 스택 초기화 함수
void init(Stack* s) {
    s->top = -1;
}

// 스택이 비었는지 확인
int isEmpty(Stack* s) {
    return s->top == -1;
}

// 스택이 가득 찼는지 확인
int isFull(Stack* s) {
    return s->top == MAX_SIZE - 1;
}

// push: 데이터 삽입
void push(Stack* s, int value) {
    if (isFull(s)) {
        printf("스택이 가득 찼습니다!\n");
        return;
    }
    s->data[++(s->top)] = value;
}

// pop: 데이터 꺼내기
int pop(Stack* s) {
    if (isEmpty(s)) {
        printf("스택이 비어있습니다!\n");
        return -1;
    }
    return s->data[(s->top)--];
}

// peek: 맨 위 값 확인 (삭제 안함)
int peek(Stack* s) {
    if (isEmpty(s)) {
        printf("스택이 비어있습니다!\n");
        return -1;
    }
    return s->data[s->top];
}

// 테스트용 main 함수
int main() {
    Stack s;
    init(&s);

    push(&s, 10);
    push(&s, 20);
    push(&s, 30);

    printf("Top: %d\n", peek(&s)); // 30
    printf("Pop: %d\n", pop(&s));  // 30
    printf("Pop: %d\n", pop(&s));  // 20
    printf("Pop: %d\n", pop(&s));  // 10
    printf("Pop: %d\n", pop(&s));  // 스택이 비어있습니다!

    return 0;
}