#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MaxSize 10
typedef struct {
char name[20];
}ElemType;
typedef struct {
ElemType data[MaxSize];
int top;//栈顶指针,记录数组下标
}SqStack;
void InitStack(SqStack *S);
bool StackEmpty(SqStack *S);
bool Push(SqStack *S,ElemType x);
bool Pop(SqStack *S,ElemType *x);
bool GetTop(SqStack *S,ElemType *x);
void InitStack1(SqStack *S);
bool StackEmpty1(SqStack *S);
bool Push1(SqStack *S,ElemType x);
bool Pop1(SqStack *S,ElemType *x);
bool GetTop1(SqStack *S,ElemType *x);
int main() {
ElemType a={"aaa"},b={"bbb"},c={"ccc"};
SqStack *S = (SqStack *) malloc(sizeof(SqStack));
InitStack1(S);
StackEmpty1(S);
ElemType e;
Push1(S, a);
GetTop1(S,&e);
Push1(S,b);
GetTop1(S,&e);
Pop1(S,&e);
return 0;
}
/*以下的函数是基于第一个方式,top=-1的情况
*
*
*
* */
void InitStack(SqStack *S) {
S->top=-1;
}
bool StackEmpty(SqStack *S){
if (S->top==-1)
return true;
else
return false;
}
bool Push(SqStack *S,ElemType x){//增,进栈
if (S->top==MaxSize-1)
return false;
S->top++;
S->data[S->top]=x;//也可以S->data[++S->top]=x;
return true;
}
bool Pop(SqStack *S,ElemType *x){//删,出栈
if (S->top == -1)
return false;
*x=S->data[S->top];//也可以*x=S->data[S->top--]
S->top--;
return true;
}
bool GetTop(SqStack *S,ElemType *x){//查
if (S->top == -1)
return false;
*x=S->data[S->top];
return true;
}
/*以下的函数是基于第二个方式,top=0的情况
* top指向栈顶元素后面空的那块位置
*
* */
void InitStack1(SqStack *S){
S->top=0;
}
bool StackEmpty1(SqStack *S){
if (S->top==0)
return true;
else
return false;
}
bool Push1(SqStack *S,ElemType x){
if (S->top==MaxSize)
return false;
S->data[S->top++]=x;
return true;
}
bool Pop1(SqStack *S,ElemType *x){
if (S->top == 0)
return false;
*x=S->data[--S->top];
return true;
}
bool GetTop1(SqStack *S,ElemType *x){
if (S->top == 0)
return false;
*x=S->data[S->top];
return true;
}
/*共享栈
*
*
*
*
* */
typedef struct {
ElemType data[MaxSize];
int top0;
int top1;
}ShStack;
void InitStack2(ShStack *S){
S->top0=-1;
S->top1=MaxSize;
}
bool IsFull2(ShStack *S){
if(S->top1==1+S->top0){
return true;
} else
return false;
}