栈: 数据进出,类向箱子放东西和拿东西,先进后出,或者说后进先出。栈分为静态栈和动态栈两种,静态栈用数组实现,
动态栈用链表实现。算法 出栈 入栈(压栈),遍历,清空。
创建栈:
#define MaxSize 100 //定义栈中元素的最大个数
typedef struct{
Elemtype data[MaxSize];
int top;
}SqStack;
入栈与出栈:
入栈:
bool Push(SqStack &S,Elemtype x){
if(S.top==MaxSize-1) //栈满报错
return false;
S.data[++S.top]=x; //指针先加1,再入栈
return true;
}
出栈:
bool Pop(SqStack &S,Elemtype x){
if(S.top==-1) //栈空,报错
return false;
x=S.data[S.top--]; //先出栈,再减1
return true;
}
读栈顶元素:
bool GetTop(SqStack S,Elemtype &x){
if(S.top==-1) return false; //栈空报错
x=S.data[S.top]; //记录栈顶元素
return true;
}