Jiyong's STUDY

[기초] 스택 자료구조의 ADT 본문

보안/리버싱, 어셈블리

[기초] 스택 자료구조의 ADT

Kingjiyong 2020. 7. 16. 15:23

자료구조에서 배울 수 있는 stack 자료구조에 대한 설명. 

 

일단 stack 자료구조의 ADT와 예제

 

func.h

 

#pragma once

#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);
Data SPop(Stack* pstack);
Data SPeek(Stack* pstack);

#endif

 

 

 

func.c

 

#include <stdio.h>
#include <stdlib.h>
#include "func.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 Error!");
exit(-1);
}

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

 

 

 

main.c 

 

#include <stdio.h>
#include "func.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

 

push는 값을 넣는 것, pop은 값을 꺼내는 것, peek는 맨 위의 값을 들여다 보는 것.

 

또한 stack 자료구조의 형태는 제일 먼저 넣은 것이 제일 마지막에 나오는 구조로 되어있음.

줄여서 후입선출 방식의 자료구조. 영어로 LIFO(Last-In, First Out)의 구조

 

코드 해석은 알아서