자료구조 : 스택(Stack) 배열

ROK·2022년 10월 17일
0

열혈 자료구조

목록 보기
14/30

배열을 사용한 스택 자료구조 구현

헤더파일

#ifndef __AB_STACK_H__
#define __AB_STACK_H__

#define TRUE 1
#define FALSE 0
#define STACK_LEN 100

typedef int Data;

typedef struct _arrayStack
{
   Data stackArr[STACK_LEN];
   int topIndex;
} ArrayStack;

typedef ArrayStack Stack;

void StackInit(Stack *pstack); // 초기화
int SIsEmpty(Stack *pstack);   // 비었는지 확인

void SPush(Stack *pstack, Data data); // push 연산
Data SPop(Stack *pstack);             // pop 연산
Data SPeek(Stack *pstack);            // peek 연산

#endif

소스파일

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

void StackInit(Stack *pstack)
{
   pstack->topIndex = -1;
}

int SIsEmpty(Stack *pstack)
{
   if (pstack->topIndex == -1)
   {
      return TRUE;
   }
   else
   {
      return FALSE;
   }
}

void SPush(Stack *pstack, Data data)
{
   pstack->topIndex += 1;
   pstack->stackArr[pstack->topIndex] = data;
}

Data SPop(Stack *pstack)
{
   int rIdx;

   if (SIsEmpty(pstack))
   {
      printf("Stack Memory Error!");
      exit(-1);
   }

   rIdx = pstack->topIndex;
   pstack->topIndex -= 1;

   return pstack->stackArr[rIdx];
}

Data SPeek(Stack *pstack)
{
   if (SIsEmpty(pstack))
   {
      printf("Stack Memory Erorr!");
      exit(-1);
   }

   return pstack->stackArr[pstack->topIndex];
}

메인파일

#include <stdio.h>
#include "ArrayBaseStack.h"

int main()
{
   // Stack 생성 및 초기화
   Stack stack;
   StackInit(&stack);

   // 데이터 넣기
   SPush(&stack, 1);
   SPush(&stack, 2);
   SPush(&stack, 3);
   SPush(&stack, 4);
   SPush(&stack, 5);

   // 데이터 꺼내기
   while (!SIsEmpty(&stack))
   {
      printf("%d ", SPop(&stack));
   }

   return 0;
}

결과

5 4 3 2 1
profile
하루에 집중하자

0개의 댓글