seqStack.cpp代码如下:
#include <iostream>
#include <header.h>
using namespace std;
//创建顺序栈
void seqStack::init(int size)
{
data = new int[size];
top = -1;
cout<<"创建成功"<<endl;
return;
}
//判空
int seqStack::stack_empty()
{
return top==-1;
}
//入栈
void seqStack::stack_push(int e)
{
//先加后入
top+=1;
data[top]=e;
return;
}
//出栈
void seqStack::stack_pop()
{
if(stack_empty())
{
cout<<"出栈失败"<<endl;
return;
}
//先弹后减
cout<<data[top]<<"出栈成功"<<endl;
top-=1;
return;
}
//遍历栈
void seqStack::stack_show()
{
if(stack_empty())
{
cout<<"出栈失败"<<endl;
return;
}
cout<<"栈中从顶到底的元素分别是";
for(int i = top ; i>=0 ; i--)
{
cout<<data[i]<<" ";
}
cout<<endl;
return;
}
//销毁
void seqStack::xh()
{
delete []data;
data = nullptr;
cout<<"销毁成功"<<endl;
return;
}
hearder.h代码如下:
#ifndef HEADER_H
#define HEADER_H
const int MAX = 20;
class seqStack
{
private:
int *data;
int top;
public:
//创建顺序栈
void init(int size);
//判空
int stack_empty();
//入栈
void stack_push(int e);
//出栈
void stack_pop();
//遍历栈
void stack_show();
//销毁
void xh();
};
#endif // HEADER_H
main.cpp代码如下:
#include <iostream>
#include <header.h>
using namespace std;
int main()
{
seqStack s;
//创建顺序栈
s.init(MAX);
//入栈
s.stack_push(4);
s.stack_push(3);
s.stack_push(2);
s.stack_push(1);
//遍历
s.stack_show();
//出栈
s.stack_pop();
//遍历
s.stack_show();
//销毁
s.xh();
return 0;
}
结果如下图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/e14315123172a3602a533efa5abac4ac.png)