스택 구현.

#include "stdio.h"
#include "stdlib.h"

typedef struct{
int key;
}Element;

typedef struct{
int max_size;
int top;
Element *element;

}Stack;

Stack *create_stack(int max_size);
int is_empty_stack(Stack *stk);
int is_full_stack(Stack *stk);
int push_stack(Stack *stk, Element elm);
int pop_stack(Stack *stk, Element *elm);
void destroy_stack(Stack *stk);

int main(){

int i;
Element ele;
Stack *stack;

stack = create_stack(5);

for(i=0;i<5;i++){

ele.key = i+1;
printf("push %d ",ele.key);
push_stack(stack,ele);
if(is_full_stack(stack)){
printf("now stack is full ");
}
}

for(i=0;i<5;i++){
ele.key=i;
pop_stack(stack,&ele);
printf("pop %d",ele.key);
if(is_empty_stack(stack)){
printf("now stack is empty ");
}
}

destroy_stack(stack);

return 0;}


Stack *create_stack(int max_size)
{
Stack *tmp;

tmp = (Stack *) malloc(sizeof(Stack));
tmp->max_size = max_size;
tmp->top = -1;
tmp->element = (Element *)
malloc(sizeof(Element) *max_size);
return(tmp);
}

int is_full_stack(Stack *stk)
{
if(stk->top == stk->max_size - 1) return (1);
else return(0);
}

int is_empty_stack(Stack *stk)
{
if(stk->top == -1) return(1);
else return (0);
}

int push_stack(Stack *stk, Element elm)
{
if(is_full_stack(stk)) return(-1);

stk->top ++;
stk->element[stk->top] = elm;
return(1);
}

int pop_stack(Stack *stk, Element *elm)
{
if(is_empty_stack(stk)) return(-1);

*elm = stk->element[stk->top];
stk->top --;
return(1);
}

void destroy_stack(Stack *stk)
{
free(stk->element);
free(stk);
}

by muzie | 2004/10/15 19:41 | STUDY | 트랙백 | 덧글(0)

트랙백 주소 : http://muzie.egloos.com/tb/430983
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]

:         :

:

비공개 덧글

◀ 이전 페이지          다음 페이지 ▶