C Programming
main.c(스택)
빛하루
2023. 8. 24. 17:30
※main.c파일
#include <stdio.h>
#include "stack.h"
int main(void)
{
Stack s1, s2;
//Stack stacks[10];
s1.tos = 0;
s2.tos = 0;
push(&s1,100); //구조체 자료는 인자를 전달할 때 오버헤드를 줄이기 위해 포인터를 쓴다.
push(&s1,200);
push(&s1,300);
printf("s1 1st pop() : %d\n",pop(&s1));
printf("s1 2nd pop() : %d\n",pop(&s1));
printf("s1 3rd pop() : %d\n",pop(&s1));
pop(&s1);
push(&s2,900);
push(&s2,800);
push(&s2,700);
printf("s2 1st pop() : %d\n",pop(&s2));
printf("s2 2nd pop() : %d\n",pop(&s2));
printf("s2 3rd pop() : %d\n",pop(&s2));
return 0;
}
※stack.h파일
#ifndef STACK_H
#define STACK_H
#define STACKSIZE 100
typedef struct stack {
int array[STACKSIZE];
int tos;
}Stack;
void initStack(Stack *s);
void push(Stack *s, int data);
int pop(Stack *s);
#endif
※stack.c파일
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void initStack(Stack *s)
{
s->tos = 0;
}
void push(Stack *s, int data)
{
if (s->tos == STACKSIZE) {
fprintf(stderr,"STACK IS FULL");
exit(1);
}
s->array[s->tos] = data;
++s->tos;
}
int pop(Stack *s)
{
if (s->tos == 0) {
frpintf(stderr,"STACK IS EMPTY");
exit(2);
}
--s->tos;
return s->array[s->tos];
}