본문 바로가기

프로그래밍/자료구조

배열로 Stack 구현

#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 10
#define ERROR_CODE 60000

typedef int element;

//스택 구조체
typedef struct{
	element stack[STACK_SIZE];
	int top;
}ArrayStack;

//stack만들기
ArrayStack* createStack(){
	ArrayStack *s=(ArrayStack*)malloc(sizeof(ArrayStack));
	s->top=-1;
	return s;
}

//스택이 비었는지 검사
int isEmpty(ArrayStack *s){   
	if(s->top==-1)return 1;
	else return 0;
}

//스택이 가득 찼는지 검사
int isFull(ArrayStack *s){    
	if(s->top>=STACK_SIZE-1) return 1;
	else return 0;
}

//push
int push(ArrayStack *s, int data){
	if(isFull(s)){
		printf("stack overflow\n");
		return ERROR_CODE;
	}
	s->top++;
	s->stack[s->top]=data;
	return 1;
}

//pop
element pop(ArrayStack *s){
	element temp;
	if(isEmpty(s)){
		printf("stack underflow\n");
		return ERROR_CODE;
	}
	temp= s->stack[s->top];
	s->top--;
	return temp;
	//return s->stack[s->top--];
}

//peek
element peek(ArrayStack *s){
	if(isEmpty(s)){
		printf("stack is Empty\n");
		return ERROR_CODE;
	}
	return s->stack[s->top];
}

void printStack(ArrayStack *s){
	int index;
	if(isEmpty(s)) return ;
	index=s->top;
	while(index!=-1){
		printf("%d\n",s->stack[index--]);
	}
}

int main(){
	ArrayStack *s1, *s2;
	s1 = createStack();
	s2 = createStack();
	push(s1, 10);
	push(s2, 100);
	return 0;
}