栈的顺序存储实现
一、定义
#define MaxSize 10
typedef struct{
int data[MaxSize];
int top;
}SqStack;
二、初始化时top=-1
2.1初始化
bool initSqStack(SqStack &S){
int top = -1;
return true;
}
2.2入栈
bool push(SqStack &S, int x){
if(S.top == MaxSize - 1){
return false;
}
S.top = S.top + 1;
S.data[S.top] = x;
return true;
}
2.3出栈
bool pop(SqStack &S, int &x){
if(S.top == -1){
return false;
}
x = S.data[S.top];
S.top = S.top - 1;
return true;
}
2.4获得栈顶元素
int getElem(SqStack &S){
if(S.top == -1){
return false;
}
return L.data[S.top];
}
2.5判断栈空
bool empty(SqStack S){
if(S.top == -1){
return true;
}else{
return false;
}
}
2.6判断栈满
bool full(SqStack S){
if(S.top == MaxSize -1){
return true;
}else{
return false;
}
}
三、初始化时top=0
3.1初始化
bool initSqStack(SqStack &S){
S.top = 0;
return true;
}
3.2入栈
bool push(SqStack &S, int x){
if(S.top == MaxSize){
return false;
}
S.data[S.top] = x;
S.top = S.top + 1;
return true;
}
3.3出栈
bool pop(SqStack &S, int &x){
if(S.top == 0){
return false;
}
S.top= S.top - 1;
x = S.data[S.top];
return true;
}
3.4获得栈顶元素
int getElem(SqStack S){
if(S.top == 0){
return false;
}
return S.data[--S.top];
}
3.5判断栈空
bool empty(SqStack S){
if(S.top == 0){
return true;
}else{
return false;
}
}
3.6判断栈满
bool full(SqStack &S){
if(S.top == MaxSize){
return true;
}else{
return false;
}
}
四、共享栈
4.1定义
两个栈共享一片内存空间,两个栈从两边往中间增长
#define MaxSize 10
typedef struct{
int data[MaxSize];
int top0;
int top1;
}ShStack;
4.2初始化
bool initShStack(ShStack &S){
S.top0 = -1;
S.top1 = MaxSize;
return true;
}
4.3判断栈满
bool full(ShStack S){
if(S.top0 + 1 == S.top1){
return true;
}else{
return false;
}
}