1. 定义头文件
#ifndef __SQSTACK_H__
#define __SQSTACK_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct {
datatype *data;
int maxlen; // 栈的长度
int top; //栈顶指针
}sqstack;
//创建栈
sqstack* stack_create(int len);
//判断空栈
int stack_empty(sqstack *s);
//清空栈
void stack_clear(sqstack *s);
//判断满栈
int stack_full(sqstack *s);
//进栈
int stack_push(sqstack *s,datatype value);
//出栈
datatype stack_pop(sqstack *s);
//取栈顶
datatype stack_top(sqstack *s);
//销毁栈
void stack_free(sqstack *s);
#endif
2. 方法实现
2.1 创建栈
//创建栈
sqstack* stack_create(int len){
//先申请sqstack 结构体空间
sqstack *s;
if((s=(sqstack *)malloc(sizeof(sqstack)))== NULL){
printf("malloc failed!!!\n");
return NULL;
}
//申请结构体内部 存放数据的空间
if((s->data = (datatype *) malloc(len * sizeof(datatype))) == NULL){
printf("malloc failed!");
return NULL;
}
s->maxlen = len;
s->top = -1;
return s;
}
2.2 判空
//判断空栈
int stack_empty(sqstack *s){
return (s->top==-1 ? 1 : 0);
}
2.3 清空栈
//清空栈
void stack_clear(sqstack *s){
s->top = -1;
}
2.4 判断是否已满
//判断满栈
int stack_full(sqstack *s){
return (s->top == s->maxlen-1 ? 1 : 0);
}
2.5 入栈
int stack_push(sqstack *s,datatype value){
if(stack_full(s)){
printf(" stack is full\n");
return -1;
}
//存数
s->data[s->top+1] = value;
//top自增
s->top++;
return 1;
}
2.6 出栈
//出栈
datatype stack_pop(sqstack *s){
if(stack_empty(s)){
printf("stack is empty!!\n");
return -1;
}
s->top--;
return s->data[s->top+1];
}
2.7 取栈顶
//取栈顶
datatype stack_top(sqstack *s){
if(stack_empty(s)){
printf("stack is empty!!\n");
return -1;
}
return s->data[s->top];
}
2.8 销毁栈
//销毁栈
void stack_free(sqstack *s){
free(s->data);
s->data = NULL;
free(s);
s = NULL;
}