본문 바로가기
C and C++/C and C++ Examples

[C Examples] Stack을 활용해서 Stack 값 바꿔보기, Dynamic stack

by Henry Cho 2023. 11. 9.
728x90

Stack을 활용해서 Stack 값 바꿔보기, Dynamic stack

포스트 난이도: HOO_Junior


# Example Code 1

이번 포스트에서는 C언어의 Stack (스택) 값을 바꿔보는 예제코드를 통해 스택에 대해서 보다 더 익숙해질 수 있다. 특히 이번 예제코드에서는 동적 배열 또는 동적 스택이라고 불리는 Dynamic stack에 대해서 살펴볼 수 있다. 아래의 예제코드 1을 보면 Lottery 숫자가 스택으로 주어져있는 상황에서 사용자가 임의의 7자리 숫자를 입력하고 난 뒤에 중간 스택에 새로운 값이 추가되는 걸 확인할 수 있다. 이때 예제코드 1에서는 중간 배열의 스택이 지속적으로 추가가 되어 처음 스택보다 스택의 값이 증가하는 걸 알 수 있다.

 

반면에 예제코드 2에서는 중간에 새롭게 값이 추가됨과 동시에 기존의 중간 배열의 스택 값은 제거됨으로써 스택의 수가 유지되는 걸 알 수 있다. 마치 새로운 값에 의해 교체되는 것처럼 볼 수 있으며, 교체되는 스택 값이 필요할 때 예제코드 2를 활용할 수 있다. 나머지 코드에 대한 내용과 부분은 동일하기 때문에 예제코드 1과 2를 비교할 때 다이내믹 스택이 어떻게 처리가 되는지 부분을 집중적으로 살펴보면 스택을 이해하는데 수월하다.


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

struct StackNode {
    int value;
    struct StackNode* next;
};

struct StackNode* top = NULL;

void push(int val) {
    struct StackNode* newNode = (struct StackNode*)malloc(sizeof(struct StackNode));
    newNode->value = val;
    newNode->next = top;
    top = newNode;
}

void display() {
    struct StackNode* ptr = top;
    if (top == NULL) {
        printf("STACK IS EMPTY\n");
    } else {
        while (ptr != NULL) {
            printf("|%d|\n", ptr->value);
            ptr = ptr->next;
        }
    }
}

void winner(int winnum) {
    struct StackNode* ptr = top;
    if (top == NULL) {
        printf("STACK IS EMPTY\n");
    } else {
        while (ptr != NULL) {
            if (ptr->value == winnum) {
                printf("Congratulations, you won!\n");
                return;
            }
            ptr = ptr->next;
        }
        printf("Sorry, you need to buy more tickets!\n");
    }
}

void pop() {
    if (top == NULL) {
        printf("STACK UNDERFLOW\n");
    } else {
        struct StackNode* ptr = top;
        top = top->next;
        free(ptr);
    }
}

int main() {
    int number;
    int ticketarray[] = {4525856, 8653154, 2543679, 9543567, 5909866, 2468576, 9845645};
    printf("Pushing 7 values to the stack...\n");
    printf("Displaying the Dynamic stack:\n");
    for (int i = 0; i < 7; i++) {
        push(ticketarray[i]);
        
    }
    display();

    printf("\n\nEnter your lottery ticket number: ");
    scanf("%d", &number);
    winner(number);

    for (int i = 0; i < 3; i++) {
        pop();
    }
    push(7653459);
    for (int i = 4; i < 7; i++) {
        push(ticketarray[i]);
    }

    printf("\n\nStack after changing the middle number: \n");
    display();

    // Free the remaining nodes
    while (top != NULL) {
        pop();
    }

    return 0;
}



# Example Code 2

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

struct StackNode {
    int value;
    struct StackNode* next;
};

struct StackNode* top = NULL;

void push(int val) {
    struct StackNode* newNode = (struct StackNode*)malloc(sizeof(struct StackNode));
    newNode->value = val;
    newNode->next = top;
    top = newNode;
}

void display() {
    struct StackNode* ptr = top;
    if (top == NULL) {
        printf("STACK IS EMPTY\n");
    } else {
        while (ptr != NULL) {
            printf("|%d|\n", ptr->value);
            ptr = ptr->next;
        }
    }
}

void winner(int winnum) {
    struct StackNode* ptr = top;
    if (top == NULL) {
        printf("STACK IS EMPTY\n");
    } else {
        while (ptr != NULL) {
            if (ptr->value == winnum) {
                printf("Congratulations, you won!\n");
                return;
            }
            ptr = ptr->next;
        }
        printf("Sorry, you need to buy more tickets!\n");
    }
}

void pop() {
    if (top == NULL) {
        printf("STACK UNDERFLOW\n");
    } else {
        struct StackNode* ptr = top;
        top = top->next;
        free(ptr);
    }
}

int main() {
    int number;
    int ticketarray[] = {4525856, 8653154, 2543679, 9543567, 5909866, 2468576, 9845645};
    printf("Pushing 7 values to the stack...\n");
    printf("Displaying the Dynamic stack:\n");
    for (int i = 0; i < 7; i++) {
        push(ticketarray[i]);
    }
    display();

    printf("\n\nEnter your lottery ticket number: ");
    scanf("%d", &number);
    winner(number);

    // Remove the middle ticket number (9543567) by popping it
    struct StackNode* ptr = top;
    struct StackNode* prev = NULL;
    while (ptr != NULL && ptr->value != 9543567) {
        prev = ptr;
        ptr = ptr->next;
    }
    if (ptr != NULL) {
        if (prev != NULL) {
            prev->next = ptr->next;
        } else {
            top = ptr->next;
        }
        free(ptr);
    }

    // Insert the new value (7653459) in the middle of the stack
    struct StackNode* newNode = (struct StackNode*)malloc(sizeof(struct StackNode));
    newNode->value = 7653459;
    newNode->next = prev->next;
    prev->next = newNode;

    printf("\n\nStack after changing the middle number: \n");
    display();

    // Free the remaining nodes
    while (top != NULL) {
        pop();
    }

    return 0;
}



# github

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/dynamic_stack_keep

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/dynamic_stack_remove


 

728x90

댓글