顺序栈结构体定义及方法实现(SqStack.h):
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int ElemType;
#define STACK_INITSIZE 100//存储空间初始分配量
#define STACK_INCREAMENT 10//存储空间分配增量
struct SqStack//顺序栈
{
ElemType *base;//在栈构造之前和销毁之后,base的值为NULL
ElemType *top;//栈顶指针
int stacksize;//当前已分配的存储空间
};
//构造一个空栈
bool InitStack(SqStack &S)
{
S.base = (ElemType *)malloc(STACK_INITSIZE*sizeof(ElemType));
if(!S.base)
return false;
S.top = S.base;//栈顶指向栈底(空栈)
S.stacksize = STACK_INITSIZE;//存储空间为初始分配量
}
//销毁顺序栈
void DestroyStack(SqStack &S)
{
free(S.base);//释放栈空间
S.top = S.base = NULL;//栈顶,栈底指针为空
S.stacksize = 0;//当前已分配的存储空间清空
}
//置空栈
void ClearStack(SqStack &S)
{
S.top = S.base;//栈顶指针指向栈底
}
//判断栈是否是空栈
bool StackEmpty(SqStack S)
{
return S.top == S.base?true:false;
}
//计算栈的长度
int StackLength(SqStack S)
{
return S.top - S.base;
}
//返回栈顶元素
bool GetTop(SqStack S,ElemType &e)
{
if(S.top>S.base)
{
e = *(S.top-1);
return true;
}
return false;
}
//插入元素作为新的栈顶元素
bool Push(SqStack &S,ElemType e)
{
if(S.top-S.base == S.stacksize)//栈满,补充空间
{
S.base = (ElemType *)realloc(S.base,(S.stacksize+STACK_INCREAMENT)*sizeof(ElemType));//追加存储空间
if(!S.base)
return false;
S.top = S.base+S.stacksize;//栈顶指针指向新的栈顶
S.stacksize += STACK_INCREAMENT;//更新存储空间大小
}
*S.top = e;//e入栈作为栈顶元素
S.top++;//栈顶指针上移一个存储单元
return true;
}
//删除栈顶元素并返回其值
bool Pop(SqStack &S,ElemType &e)
{
if(S.top>S.base)
{
e = *(S.top-1);//栈顶元素赋值给e
S.top--;//栈顶指针下移一个存储单元
return true;
}
return false;
}
//遍历顺序栈
void StackTraverse(SqStack S)
{
ElemType *p = S.base;//伴随指针p指向栈底
for(;p<=S.top;p++)
cout<<*p<<" ";
cout<<endl;
}
顺序栈方法测试(SqStackTest.cpp):
#include<iostream>
#include"SqStack.h"
using namespace std;
int main()
{
SqStack S;
int num;
if(InitStack(S)) cout<<"顺序栈创建成功"<<endl;
if(StackEmpty(S)) cout<<"此栈为空栈"<<endl;
for(int i = 0;i<10;i++)
Push(S,i);
cout<<"此栈中元素个数为"<<StackLength(S)<<endl;
if(Pop(S,num)) cout<<"从栈中提取栈顶元素"<<num<<endl;
if(GetTop(S,num)) cout<<"现在的栈顶元素为"<<num<<endl;
cout<<"遍历栈中所有元素:";
StackTraverse(S);
ClearStack(S);
if(StackEmpty(S)) cout<<"此栈为空栈"<<endl;
DestroyStack(S);
cout<<"销毁栈后,S.base ="<<S.base<<" S.top="<<S.top<<" S.size="<<S.stacksize<<endl;
}