一、创建sqstack.h头文件,定义栈并声明基本操作函数
#pragma once
#include<iostream>
using namespace std;
#define MAXSIZE 100 //可能达到的最大空间
//定义栈
struct SqStack
{
int* base; //栈底指针
int* top; //栈顶指针
int stacksize; //栈可用最大容量
};
//初始化
bool InitStack(SqStack& S);
//插入 入栈
bool Push(SqStack& S, int e);
//删除
bool Pop(SqStack& S, int& e);
//遍历
void PrintSqStack(SqStack S);
//判断是否为空
bool StackEmpty(SqStack S);
//栈长度
int StackLength(SqStack S);
//清空
bool ClearStack(SqStack& S);
//销毁
bool DestoryStack(SqStack& S);
二、创建sqstack.cpp源文件,将声明的基本操作具体实现
#include"sqstack.h"
//初始化
bool InitStack(SqStack& S)
{
S.base = new int[MAXSIZE]; //分配空间,base指向数组首地址 栈底
if (!S.base)
{
exit(0); //分配失败退出系统
}
S.top = S.base; //栈顶指针等于栈底指针 初始化为空表
S.stacksize = MAXSIZE; //最大容量
return true;
}
//插入 入栈
bool Push(SqStack& S, int e)
{
if (S.top - S.base == S.stacksize) //判断栈是否已满
{
return false;
}
*S.top++ = e; //给*top赋值,并让top指针指向下一空间
return true;
}
//删除
bool Pop(SqStack& S, int& e)
{
if (S.top == S.base) //判断栈是否为空
{
return false;
}
e = *--S.top; //先栈顶下移,再将值解引用赋值给e
return true;
}
//遍历
void PrintSqStack(SqStack S)
{
while (S.top != S.base)
{
S.top--;
cout << *S.top << endl;
}
}
//判断是否为空
bool StackEmpty(SqStack S)
{
if (S.top == S.base)
{
return true;
}
else
{
return false;
}
}
//栈长度
int StackLength(SqStack S)
{
return S.top - S.base;
}
//清空
bool ClearStack(SqStack& S)
{
if (S.base)
{
S.top = S.base;
return true;
}
}
//销毁
bool DestoryStack(SqStack& S)
{
if (S.base)
{
delete S.base;
S.stacksize = 0;
S.base = S.top = NULL;
}
return true;
}
三、在主函数中测试
#include<iostream>
using namespace std;
#include"sqstack.h" //包含头文件
int main()
{
//1.创建栈S,并初始化
SqStack S;
InitStack(S);
//2.插入元素
int arr[5] = { 5,4,3,2,1 };
for (int i = 0; i < 5; i++)
{
Push(S, arr[i]);
}
cout << "插入后打印:" << endl;
//3.遍历
PrintSqStack(S);
//4.删除
int e;
Pop(S, e);
cout << "元素" << e << "已删除" << endl;
cout << "删除后打印:" << endl;
PrintSqStack(S);
//5.判断是否为空
if (StackEmpty(S))
{
cout << "栈为空" << endl;
}
else
{
//6.栈的元素个数
cout << "栈不为空元素个数为:" << StackLength(S) << endl;
}
//7.清空
ClearStack(S);
cout << "清空后打印:" << endl;
PrintSqStack(S);
//8.销毁
DestoryStack(S);
system("pause");
return 0;
}
四、最终效果