[자료구조] 스택 Stack C

K근형·2023년 12월 23일
0

자료구조

목록 보기
6/12

배열을 이용한 스택

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

#pragma warning (disable : 4996)

#define MAX_SIZE 5

typedef struct stack
{
    int arr[MAX_SIZE];
    int top;
}stack;

void push(stack* p, int data);
int pop(stack* p);
void displayStack(stack* p);

int main(void)
{
    stack stk; //스택 구조체 변수 선언
    int choice, data;
    stk.top = -1;

    while(1)
    {
        system("clear");
        printf("\n\n\t\t * Stack with linked list *\n");
        printf("1. push    2. pop    3. print    4. clear    0. terminate\n");
        printf("choice: ");
        scanf("%d", &choice);

        switch (choice)
        {
        case 1:
            printf("\n\n삽입할 정수를 입력하세요: ");
            scanf("%d", &data);
            push(&stk, data);
            break;
        case 2:
            data = pop(&stk);

            if (data != -1)
            {
                printf("\n\n\t\t%d pop!", data);
            }
            break;
        case 3:
                displayStack(&stk);
            break;
        case 4:
                //삭제된 것처럼 논리적인 구현
                stk.top = -1;
            break;
        case 0:
            return 0;
        }

        printf("\n\n\t\t");
        printf("read"); //printf("pause")

    }
    return 0;
}

void push(stack* p, int data)
{
    // 더이상 삽입할 수 없는 상태
    if(p->top == MAX_SIZE - 1)
    {
        printf("\n\n\t\tstack overflow\n");
    }
    ++(p->top); //top을 증가시키고
    p->arr[p->top] = data; //데이터 저장
}

int pop(stack* p)
{
    if(p->top == -1)
    {
        // 더이상 삭제할 수 없는 상태
        printf("\n\n\t\tstack underflow\n");
        return -1;
    }
    //실제로 데이터가 삭제되는 것이 아니다.(물리적인 삭제X)
    // top의 값을 1 감소해서 삭제 된 것처럼 생각하는 것이다.(논리적인 삭제O)
    int delValue = p->arr[p->top]; //삭제된 값 저장
    --(p->top);

    return delValue;
}

void displayStack(stack* p)
{
    if (p->top == -1)
    {
        printf("\n\n\t\t저장된 데이터는 존재하지 않습니다.\n");
        return;
    }

    printf("\nstack display(LIFO)");
    for(int i = p->top; i >= 0; i--)
    {
        printf("%d", p->arr[i]);
    }
    puts("");
}

✔️ 연결리스트를 이용한 스택 c

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

#pragma warning (disable : 4996)

typedef struct node
{
    int value;
    struct node* next;
}node;

node* head = NULL;

void push(int data);
int pop();
void displayStack();
void clearStack();


int main(void)
{
    int choice, data;
    while(1)
    {
        system("clear");
        printf("\n\n\t\t * Stack with linked list *\n");
        printf("1. push    2. pop    3. print    4. clear    0. terminate\n");
        printf("choice: ");
        scanf("%d", &choice);

        switch (choice)
        {
        case 1:
            printf("\n\n삽입할 정수를 입력하세요: ");
            scanf("%d", &data);
            push(data);
            break;
        case 2:
            data = pop(); //삭제된 값 리턴
            if (data != -1)
            {
                printf("\n\n\t\t%d pop!\n", data);
            }
            break;
        case 3:
            displayStack();
            break;
        case 4:
            clearStack();


            break;
        case 0:
                clearStack(); //memory leak 발생을 제거하기 위해
            return 0;
        }

        printf("\n\n\t\t");
        system("read"); //printf("pause")// Read?


    }
    return 0;
}

void push(int data)
{
    //메모리를 할당하고 가는 구조가 아니기 때문에 overflow가 없음!
    // 맨 앞 삽입 : Last In First Out, LIFO
    node* newNode;
    newNode = (node*)malloc(sizeof(node)); //메모리 할당 후
    newNode->value = data; //저장
    newNode->next = NULL;

    if (head == NULL)
    {
        head = newNode;
        return;
    }

    newNode->next = head;
    head= newNode;
}

int pop()
{
    // 맨 앞 삭제
    if(head == NULL)
    {
        // 더이상 삭제할 수 없는 상태
        printf("\n\n\t\tstack underflow\n");
        return -1;
    }

    //실제 삭제되는 코드: 물리적인 삭제
    node* delNode = head;
    head = head->next;
    int delValue = delNode->value; //삭제할 값 저장
    free(delNode); //삭제
    return delValue; //삭제된 값 리턴
}

void displayStack()
{
    if (head == NULL)
    {
        printf("\n\n\t\t저장 된 데이터가 없습니다.\n");
        return;
    }

    system("clear");
    printf("\nstack display(LIFO): ");
    node* curNode = head;

    while (curNode) //방문 노드가 있다면? (마지막 노드까지 순회)
    {
        printf("%d ", curNode->value);
        curNode = curNode->next;
    }
    puts("");
}

void clearStack()
{
    if (head == NULL)
    {
        return;
    }

    //실직적인 삭제(물리적인 삭제 수행된다.)
    // 모든 노드 제거
    // 첫 노드 제거 -> 반복
    while(head) // head != NULL
    {
        node* delNode = head;
        head = head->next;
        free(delNode); //삭제
    }
}

진법 변환 c

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

#pragma warning (disable : 4996)

typedef struct node
{
    int value;
    struct node* next;
}node;

node* head = NULL;

void conversionBin(int n);
void conversionN(int n, int changeN);
void displayN(int n, int changeN);
void _clear();

int main()
{
    int n;
    printf("10진수를 입력 하세요: ");
    scanf("%d", &n);

    int changeN;
    printf("몇 진수로 변환하시겠습니까? ");
    scanf("%d", &changeN);

    conversionBin(n); //2진수로 변환
    displayN(n, 2); // 2진수 출력
    _clear();

    conversionN(n, changeN);
    displayN(n, changeN); // ?진수 출력
    _clear();
}

void conversionN(int n, int changeN)
{
    node* newNode;
    while(n / changeN >= 0)
    {
        newNode = (node*)malloc(sizeof(node));
        newNode->value = n % changeN;
        newNode->next = NULL;

        if (head == NULL)
        {
            //첫 노드만 head와 연결
            head = newNode;
        }
        else
        {
            //두 번째 노드부터는 맨 앞 추가
            newNode->next = head;
            head = newNode;
        }
        n = n / changeN;

        if(n == 0)
        {
            break;
        }
    }
}


void conversionBin(int n)
{
    node* newNode;
    while(n / 2 >= 0)
    {
        newNode = (node*)malloc(sizeof(node));
        newNode->value = n % 2;
        newNode->next = NULL;

        if (head == NULL)
        {
            //첫 노드만 head와 연결
            head = newNode;
        }
        else
        {
            //두 번째 노드부터는 맨 앞 추가
            newNode->next = head;
            head = newNode;
        }
        n = n / 2;

        if(n == 0)
        {
            break;
        }
    }
}

void displayN(int n, int changeN)
{
    if (head == NULL)
    {
        printf("\n\n\t\t저장 된 데이터가 없습니다.");
        return;
    }

    system("clear");
    node* curNode = head;

    printf("\n\n\t\t%d => ", n);
    while (curNode) //방문 노드가 있다면? (마지막 노드까지 순회)
    {
        if(curNode->value >= 10)
        {
            printf("%c", (curNode->value + 55));
        }
        else
        {
            printf("%d", curNode->value);
    }
    curNode = curNode->next;
}
printf("(%d)\n", changeN);

}

void _clear()
{
if (head == NULL)
{
return;
}

//실직적인 삭제(물리적인 삭제 수행된다.)
// 모든 노드 제거
// 첫 노드 제거 -> 반복
while(head) // head != NULL
{
    node* delNode = head;
    head = head->next;
    free(delNode); //삭제
}

}

profile
진심입니다.

0개의 댓글