头文件:
typedef struct{ SElemtype data[MAXSIZE]; //存放的数据 int top; //指向栈顶的指针 }SqStack; class StackClass { public: StackClass(); ~StackClass(); SqStack* InitStack(); bool DestroyStack(SqStack *S); bool ClearStack(SqStack*S); bool IsEmptyStack(SqStack*S);//判断是否为空栈 SElemtype GetTop(SqStack*S);//返回栈顶元素 bool PushData(SqStack * S,SElemtype e); //入栈 bool PopData(SqStack * S,SElemtype* e);//出栈 int GetStackLength(SqStack * S);//返回栈的个数 }
实现cpp文件:
//入栈操作 bool StackClass::PushData(SqStack * S,SElemtype e) { //判断是否栈已经满了 if (S->top == MAXSIZE - 1) { cout << "栈已经满了,无法继续入栈!" << endl; return false; } S->top ++; S->data[S->top] = e; return true; } //出栈操作 bool StackClass::PopData(SqStack * S,SElemtype* e) { //首先判断是否为空栈 if (S->top == -1) { return false; } *e = S->data[S->top]; S->top--; //移动栈顶指针的位置就可以了 return true; } //求栈的长度 int StackClass::GetStackLength(SqStack * S) { int cur_length = S->top + 1; return cur_length; } //判断是否为空栈 bool StackClass::IsEmptyStack(SqStack*S) { int top = S->top; if (top == -1) { return true; } return false; } //返回栈顶元素 SElemtype StackClass::GetTop(SqStack*S){ //返回栈顶元素 if (S->top == -1) { cout << "当前为空栈" << endl; return 0; } return S->data[S->top]; } //清空栈 bool StackClass::ClearStack(SqStack*S) { S->top =-1; //将数据清空 return true; } //初始化栈 SqStack* StackClass::InitStack() { SqStack * S; S->top = -1; return S; } //销毁栈 bool StackClass::DestroyStack(SqStack *S) { delete S; return true; }