배열을 사용한 스택 자료구조 구현
헤더파일
#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;
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