数据结构(C++)——顺序栈
顺序栈结构
#include<iostream> #define MaxSize 50 using namespace std; typedef int ElemType; typedef struct { ElemType data[MaxSize]; int top; }SqStack;
初始化栈
void InitStack(SqStack &S){ //初始化栈 S.top=-1; }
判断是否为空栈
bool IsEmptyStack(SqStack &S){ //判断是否为空栈 return S.top==-1; }
压栈
bool Push(SqStack &S,ElemType e){ //进栈 if(S.top==MaxSize-1){ //栈满,报错 return false; } S.data[++S.top]=e; //指针先加一,在入栈 return true; }
出栈
bool Pop(SqStack &S,ElemType &x){ //出栈 if(S.top==-1){ return false; //空栈,报错 } x=data[S.top--]; return true; }
读栈顶上的元素
bool GetTop(SqStack &S,ElemType &x){ //读栈顶上的元素 if(S.top==-1){ return false; //空栈,报错 } x=data[S.top]; return true; }