c语言 栈的操作

2024-11-23 05:16:51
推荐回答(1个)
回答1:

#include
#include

#define Max 100

typedef char T;

typedef struct MyStack
{
T aa[Max];
unsigned int p;

} stack;

//创建空栈
stack* createEmptyStack()
{
stack* st = (stack *)malloc(sizeof(stack));
int i=0;
for(i=0;i st->aa[i]=0;
st->p=0;
return st;
};

//栈判空
int isEmpty(const stack* st)
{
if(st->p==0) return 1;
else return 0;
};

//求栈的大小
unsigned int size(const stack* st)
{
return st->p;
};

//push操作
void push(stack* st,const T a)
{
st->p=st->p+1;
if(st->p==Max)
{
printf("栈满\n");
st->p--;
return;
}
st->aa[st->p]=a;
};

//pop操作
T pop(stack* st)
{
if(isEmpty(st))
{
printf("栈空");
return NULL;
}
char t=st->aa[st->p];
st->p=st->p-1;
printf("%c ",t);
return t;
};

//栈销毁
void destroy(stack* st)
{
free(st);
};

int main()
{

stack* st = createEmptyStack();
if(isEmpty(st)) printf("MyStack is empty\n");
else printf("MyStack is not empty\n");
push(st,'a');
push(st,'b');
push(st,'c');
push(st,'d');
push(st,'e');
printf("%d\n",size(st));
while(!isEmpty(st)) pop(st);
destroy(st);
system("pause");
return 0;
}