作业需求:
封装一个顺序栈,并封装其相应的操作:判空、入栈、出栈、遍历栈、销毁
实现过程:
1.头文件
#ifndef WORK01_H
#define WORK01_H
#include <iostream>
using namespace std;
class seqstack
{
int *date;
int top;
public:
int size;
void init();
int empty();
int full();
void push(int e);
void show();
void pop();
void free();
};
#endif // WORK01_H
源文件
#include <iostream>
#include<work01.h>
using namespace std;
void seqstack::init()
{
date=new int[size];
top=-1;
}
int seqstack::empty()
{
return top==-1;
}
int seqstack::full()
{
return top==size-1;
}
void seqstack::push(int e)
{
if(full())
{
cout <<"入栈失败"<<endl;
return;
}
top++;
date[top]=e;
cout <<"入栈成功"<<endl;
}
void seqstack::show()
{
if(empty())
{
cout<<"遍历失败"<<endl;
return;
}
cout<<"栈中从栈顶到栈底元素分别是:"<<endl;
for(int i=top; i>=0; i--)
{
cout << date[i]<<" ";
}
cout<<endl;
}
void seqstack::pop()
{
if(empty())
{
cout<<"出栈失败"<<endl;
}
cout<<date[top]<<"出栈成功"<<endl;
top--;
}
void seqstack::free()
{
delete date;
date=nullptr;
cout<<"销毁成功"<<endl;
}
3.测试文件:
#include <iostream>
#include<work01.h>
using namespace std;
int main()
{
seqstack q;
q.size=20;
q.init();
if(q.empty())
{
cout<<"栈为空"<<endl;
}else
{
cout<<"栈为非空"<<endl;
}
q.push(12);
q.push(5);
q.push(3);
q.push(9);
q.show();
q.pop();
q.show();
q.free();
return 0;
}
实现结果: