一、栈的基本概念
ps:
二、栈的顺序存储实现
1.顺序栈的定义
//顺序栈的定义
#define MaxSize 10
typedef struct{
Elemtype data[MaxSize]//静态数组存放栈中元素
int top;//栈顶指针
}SqStack;
2.初始化操作
①top=-1的情况
void InitStack(SqStack &S){
S.top=-1;
}
②top=0的情况
void InitStack(SqStack &S){
S.top=0;
}
3.进栈操作
①top=-1的情况
bool Push(SqStack &S,Elemtype x){
if(S.top==MaxSize-1)return false;
S.top=S.top+1;
S.data[S.top]=x;
//以上两句等价于S.data[++top]=x;
return true;
}
②top=0的情况
bool Push(SqStack &S,Elemtype x){
if(S.top==MaxSize)return false;
S.data[S.top]=x;
S.top=S.top+1;
//以上两句等价于S.data[top++]=x;
return true;
}
4.出栈操作
①top=-1的情况
bool Pop(SqStack &S,Elemtype &x){
if(S.top==-1)return false;
x=S.data[S.top];
S.top=S.top-1;
//以上两句等价于x=S.data[S.top--];
return true;
}
②top=0的情况
bool Pop(SqStack &S,Elemtype &x){
if(S.top==0)return false;
S.top=S.top-1;
x=S.data[S.top];
//以上两句等价于x=S.data[--S.top];
return true;
}
4.读栈顶元素
bool GetTop(SqStack S,Elemtype &x){
if(S.top==-1)return false;
x=S.data[S.top];
return true;
}
5.判断栈空
①top=-1的情况
bool StackEmpty(SqStack S){
if(S.top==-1)return true;
else return false;
}
②top=0的情况
bool StackEmpty(SqStack S){
if(S.top==0)return true;
else return false;
}
三、栈的链式存储实现
1.链栈的定义
typedef struct Linknode{
Elemtype data;
struct Linknode *next;
}*LiStack;
2.进栈
相当于头插法建立单链表
3.出栈
相当于对链表头结点的“后删”操作