结构体定义:
typedef struct{
int data[MAXSIZE];
int top;
}SqStack;
链栈
typedef struct LStack{
int data;
struct LStack *next;
}LStack,*LinkStack;
共享栈
typedef struct{
int data[MAXSIZE];
int top[2];
}ShareStack;
基本操作
////静态栈基本操作
//判栈空
bool StackEmpty(SqStack a){
if(a.top==-1){
return true;
}else{
return false;
}
}
//进栈
bool Push(SqStack &a,int x){
if(a.top == MAXSIZE-1)return false;
a.data[++a.top] = x;
return true;
}
//出栈
bool Pop(SqStack &a,int &e){
if(a.top == -1)return false;
e = a.data[a.top--];
return true;
}
//读栈顶
bool GetTop(SqStack a,int &e){
if(a->top==-1)return false;
e = a.data[a.top];
return true;
}
////链栈基本操作
//初始化
void InitLStack(LinkStack &a){
a = (LStack*)malloc(sizeof(LStack));
a->next = NULL;
}
//进栈
//链栈无容量限制 想压多少压多少 无需判定是否溢出
void pushL(LinkStack &a,int x){
LinkStack s;
s = (LStack*)malloc(sizeof(LStack));
s->next = a->next;
s->data = x;
a->next = s;
}
//出栈
bool PopL(LinkStack &a,int &e){
if(a->next == NULL)return false;
LinkStack s = a->next;
e = s->data;
a = s->next;
free(s);
return true;
}
//判栈空
bool EmptyStackL(LinkStack a){
if(a->next == NULL)return true;
else return false;
}
//读栈顶
bool GetTopL(LinkStack a,int &e){
if(a->next == NULL) return false;
else{
e = a->next->data;
return true;
}
}
//销毁栈
void DestroyStackL(LinkList &a){
LinkStack b=a,s;
while(b){
s = b->next;
free(b);
b = s;
}
free(a);
}
////共享栈
//初始化
void InitStackS(ShareStack &a){
a->top[0] = -1;
a->top[1] = MAXSIZE-1;
}
//入栈(最后一个参数用来选择插入的是哪一个栈)
bool PushS(ShareStack &a,int x,int t){
if(t!=0 || t!=1){
printf("栈号无效!");
return false;
}
if(a->top[1] - a->top[0] == 1)return false;
if(t==1){
a->top[0]++;
a->data[a->top[0]] = x;
}else{
a->top[1]--;
a->data[a->top[1]] = x;
}
return true;
}
//出栈
bool PopS(ShareStack &a,int &e,int t){
if(t!=0 || t!=1){
printf("栈号无效!");
return false;
}
if(a->top[0] == -1 || a->top[1] == MAXSIZE-1)return false;
if(t==1){
e = a->data[a->top[0]];
a->top[0]--;
}else{
e = a->data[a->top[1]];
a->top[1]++;
}
return true;
}