'스택'에 해당되는 글 1건

  1. 2014.10.24 배열 스택

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

#define MAXSTACK 10

typedef struct stack
{
    char *data[MAXSTACK];
    int top;
} STACK;


void CheckStack(STACK *tmpStack);
char *PopStack(STACK *tmpStack);
void PushStack(STACK *tmpStack);
void PrintStack(STACK *tmpStack);

int main()
{
    STACK *MainStack;
    int iCount = 0;
    char checkMet;
    MainStack = (STACK*)malloc(sizeof(STACK));
    MainStack->top = -1;
    while (iCount < MAXSTACK)
    {
        MainStack->data[iCount] = NULL;
        iCount++;
    }
    while (1)
    {
        system("cls");

        printf("1. push  \n");
        printf("2. pop   \n");
        printf("3. print  \n");
        printf("4. end  \n");

        checkMet = getc(stdin);
        fflush(stdin);
        if (checkMet == '1')
        {
            printf("값을 입력해주세요 : ");
            PushStack(MainStack);

        }
        else if (checkMet == '2')
        {
            printf("POP한 항목은 : %s\n", PopStack(MainStack));
        }
        else if (checkMet == '3')
        {
            PrintStack(MainStack);
        }
        else if (checkMet == '4')
        {
            return 0;
        }
        else
        {
            printf("입력값이 잘못되었습니다");
        }
        system("pause");

    }


}

void CheckStack(STACK *tmpStack)
{
    if (tmpStack->top == -1)
    {
        printf("Stack is empty");
    }
    else
    {
        printf("Stack is not empty");
    }
}

char *PopStack(STACK *tmpStack)
{
    char *tmpString;
    if (tmpStack->top == -1)
    {
        printf("Stack is underflow");
        exit(1);
    }

    tmpString = tmpStack->data[tmpStack->top];
   
    //프린트 했을 때 보기 좋으라고 NULL 지정
    //본래라면 그냥 덮어씌어지고, 스택포인트 때문에 전혀 상관없음;
    tmpStack->data[tmpStack->top] = NULL;
    tmpStack->top--;

    return tmpString;
}

void PushStack(STACK *tmpStack)
{
    int iBuf;
    int iLen = 1;
    char *tmpString = (char*)malloc(sizeof(char));

    if (tmpStack->top > MAXSTACK-1)
    {
        printf("Stack is overflow");
        exit(1);
    }

    while ((iBuf = fgetc(stdin)) != EOF && iBuf != '\n')
    {
        tmpString[iLen - 1] = iBuf;

        tmpString = (char*)realloc(tmpString, (++iLen));
    }
    tmpString = (char*)realloc(tmpString, (--iLen));
    tmpString[iLen] = '\0';
   

    tmpStack->data[++tmpStack->top] = tmpString;

}

void PrintStack(STACK *tmpStack)
{
    int iCount = 9;
    while (iCount > -1)
    {
        printf("[%d] 번째 값 : %s\n", iCount, tmpStack->data[iCount]);
        iCount--;
       
    }
}





'IT 전공지식 > 자료구조(Data Structure)' 카테고리의 다른 글

linked list 정렬입력  (0) 2014.11.14
linked list  (0) 2014.11.14
circular queue  (0) 2014.11.07
서브스트링 연산  (0) 2014.10.23
스트링 결합연산  (0) 2014.10.23
Posted by ICT 기술 블로그