基本接口实现代码,欢迎补充
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define IBFEASIBLE -1
#define OVERFLOW -2
//#define MAXLEN 20
//#define MAXSIZE 20
typedef int Status;
typedef int ElemType; /* 元素类型为int类型*/
//顺序栈类型
typedef struct{
ElemType *elem; //存储空间的基址
ElemType *top; //栈顶位标
int size; //当前分配的存储容量
int increment; //扩容
} SqStack; //顺序栈 //顺序栈的基本接口实现
//1.初始化顺序栈
Status InitStack(SqStack &S,int size,int inc){
S.elem=(ElemType*)malloc(size*sizeof(ElemType));
if(S.elem==NULL)
return OVERFLOW;
S.top=S.elem; //置S为空栈
S.size=size; //初始容量值
S.increment=inc; //初始增量值
return OK;
}
//2.销毁顺序栈
Status DestroyStack(SqStack &S){
free(S.elem);
S.elem=NULL;
S.top=NULL;
S.size=0;
return OK;
}
//3.判断栈是否为空,为空返回
Status StackEmpty(SqStack &S){
if(S.top==S.elem){
return TRUE;
}else{
return FALSE;
}
}
//4.清空栈S
Status ClearStack(SqStack &S){
S.top=S.elem;
return OK;
}
//5.入栈操作S
Status Push(SqStack &S,ElemType e){
ElemType *newbase; //创建一个新的指针
if(S.top-S.elem>=S.size){
newbase=(ElemType*)realloc(S.elem,(S.size+S.increment)*sizeof(ElemType));//运用realloc函数进行扩容
if(newbase=NULL) return OVERFLOW;//扩容失败
S.elem=newbase;
S.top=S.elem+S.size;
S.size+=S.increment;
}
*S.top++=e;
return OK;
}
//6.出栈
Status Pop(SqStack &S, ElemType &e){
if(S.top == S.elem) return ERROR;
e = * --S.top;
return OK;
}
//7.取栈顶元素
Status GetTop(SqStack S,ElemType &e){
if(S.top == S.elem) return ERROR;
e = *(S.top -1);
return OK;
}
//8.访问函数
Status visit(ElemType e){
printf("%6d",e);
return OK;
}
//9.栈遍历
Status StackTravel(SqStack S,Status (*visit)(ElemType)){
//对栈用visit()遍历
while(S.top>S.elem){
visit (*(--S.top));
}
return OK;
}
觉得有用将点赞哦!