반응형
Stack을 이해하기 쉬운 예제입니다.
1. element.h
struct _element
{
int key;
}element;
2. stack.h
#include "element.h"
#define MAX_STACK_SIZE 5
struct _Stack
{
element items[MAX_STACK_SIZE];
int top;
}Stack;
3. main.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "stack.h"
#define TRUE 1
#define FALSE 0
unsigned char uint8_t;
unsigned int uint32_t ;
int int32_t ;
uint8_t IsEmpty(const Stack* pStack)
{
if(pStack->top == -1)
return TRUE;
else
return FALSE;
}
uint8_t IsFull(const Stack* pStack)
{
if(pStack->top >= MAX_STACK_SIZE -1)
return TRUE;
else
return FALSE;
}
void Push(Stack* pStack, element item)
{
if(IsFull(pStack) == TRUE)
{
printf("Stack is Full. Cannot Add.\n");
}
else
{
pStack->items[++pStack->top]=item;
}
}
element Pop(Stack* pStack)
{
element temp;
if(IsEmpty(pStack)==TRUE)
{
printf("Stack is empty. Cannot Remove.\n");
temp.key = -1;
return temp;
}
return pStack->items[pStack->top--];
}
void Initialize(Stack* pStack)
{
pStack->top = -1;
}
void print_stack(const Stack* pStack)
{
int i;
printf("stack : ");
if(IsEmpty(pStack) == TRUE)
{
printf("Empty\n");
}
else
{
for(i=0;i<=pStack->top;i++)
{
printf("%d ",pStack->items[i].key);
}
printf("\n");
}
}
element get_element(const int key)
{
element new_element;
new_element.key = key;
return new_element;
}
int main(void)
{
int i;
Stack my_stack;
Initialize(&my_stack);
print_stack(&my_stack);
Push(&my_stack,get_element(1));
print_stack(&my_stack);
Push(&my_stack,get_element(2));
print_stack(&my_stack);
Push(&my_stack,get_element(3));
print_stack(&my_stack);
Push(&my_stack,get_element(4));
print_stack(&my_stack);
Push(&my_stack,get_element(5));
print_stack(&my_stack);
Push(&my_stack,get_element(6));
print_stack(&my_stack);
for(i=0;i<MAX_STACK_SIZE+1;i++)
{
printf("Pop = %d\n",Pop(&my_stack).key);
print_stack(&my_stack);
}
return 0;
}
해당 결과는 아래와 같습니다.
반응형
'Computer Language > Data Structure' 카테고리의 다른 글
[자료구조] 05. Queue List 구조 예제 (C언어) (0) | 2021.07.10 |
---|---|
[자료구조] 04. Queue 배열 구조 예제 (C언어) (0) | 2021.07.10 |
[자료구조] 03. Stack Flood Fill 예제 (C언어) (0) | 2021.07.10 |
[자료구조] 01. List 구조 Baisc 예제 (C언어) (0) | 2021.07.09 |
[자료구조] 00. 자료 구조 들어가기 전, 배열구조 예제 (C언어) (0) | 2021.07.09 |
댓글