#include
#include
const int MAXSIZE = 100;
#define OK 1;
#define ERROR 0;
#define OVERFLOW 0;
#define TURE 1;
#define FALSE 0;
typedef int Status;
typedef char SElemType; //栈型数据
//顺序栈定义
typedef struct {
SElemType *base; //栈顶指针
SElemType *top; //栈底指针
int stacksize; //顺序栈可用最大容量
} SqStack; //顺序栈
//顺序栈初始化
Status InitStack(SqStack *stack){
stack->base=(SElemType*)malloc(sizeof(SElemType)*MAXSIZE); //分配空间
if(!stack->base) return OVERFLOW; //分配失败
stack->top=stack->base; //初始时让栈顶指针等于栈底指针
stack->stacksize=MAXSIZE; //栈最大容量
return OK;
}
//判断顺序栈是否为空
Status StackIsEmpty(SqStack stack) {
if(stack.top==stack.base){ //栈为空的条件:栈顶==栈底
return TURE;
} else {
return FALSE;
}
}
//求顺序栈长度
int StackLength(SqStack stack) {
if(!stack.base){
return 0;
}
return stack.top-stack.base;
}
//顺序栈清空
Status ClearStack(SqStack *stack) {
if(!stack->base){ //栈不存在
return ERROR;
} else {
stack->top=stack->base;
return OK;
}
}
//顺序栈销毁
Status DestroyStack(SqStack *stack) {
if(!stack->base){ //栈不存在
return ERROR;
} else {
free(stack->base);
stack->stacksize=0;
//stack->base=stack->top=NULL;
stack->base=NULL;
stack->top=NULL;
return OK;
}
}
//元素进入顺序栈
Status Push(SqStack *stack,SElemType elem) {
if(stack->top-stack->base==stack->stacksize){
return ERROR; //栈满
} else {
*(stack->top)=elem;
(stack->top)++;
return OK;
}
}
//顺序栈的出栈操作
Status Pop(SqStack *stack,SElemType *elem){
if(stack->top==stack->base) {
return ERROR; //下溢
} else {
(stack->top)--;
*elem = *(stack->top); //取出栈顶元素放入elem
return OK;
}
}
int main(void){
SqStack stack1;
//初始化
Status initStackResult = InitStack(&stack1);
printf("栈stack1初始化结果码:%d\n",initStackResult);
//是否为空
Status stackIsEmpty = StackIsEmpty(stack1);
printf("栈stack1为空?:%d\n",stackIsEmpty);
//清空栈
Status clearStackResult = ClearStack(&stack1);
printf("栈清空结果:%d\n",clearStackResult);
//销毁栈
/*
Status destroyStackResult = DestroyStack(&stack1);
printf("栈销毁结果:%d\n",destroyStackResult);
*/
//元素入栈
SElemType elem1='Y',elem2='C';
Status pushResult = Push(&stack1,elem1);
printf("入栈执行结果:%d\n",pushResult);
Push(&stack1,elem2); //将elem2也入栈
printf("栈顶元素值:%c\n",*(stack1.top-1));
//元素出栈
SElemType elem3; //下面取出的数据放入elem3
Status popResult = Pop(&stack1,&elem3);
printf("出栈执行结果:%d\n",popResult);
printf("出栈元素值:%c\n",elem3);
printf("栈顶元素值:%c\n",*(stack1.top-1));
printf("\nEND");
return 0;
}
标签:Status,顺序,return,实现,top,C语言,base,stack,stack1
来源: https://www.cnblogs.com/petitepluie/p/14587914.html