头文件
#ifndef seqstack1
#define seqstack1
const int stacksize=10;
class seqstack
{
public:
seqstack();
~seqstack(){};
void push(int x);
int pop();
int gettop();
int empty();
private:
int data[stacksize];
int top;
};
#endif
函数定义:
#include"h.h"
seqstack::seqstack()
{
top=-1;
}
void seqstack::push(int x)
{
if(top==stacksize-1)throw"上溢";
top++;
data[top]=x;
}
int seqstack::pop()
{
int x;
if(top==-1)throw"下溢";
x=data[top--];
return x;
}
int seqstack::gettop()
{
if(top!=-1)
return data[top];
else
return 0;
}
int seqstack::empty()
{
if(top==-1)return 1;
else return 0;
}
主函数:
#include<iostream>
#include"h.h"
using namespace std;
void main()
{
seqstack s;
if(s.empty())
cout<<"栈为空"<<endl;
else
cout<<"栈非空"<<endl;
int c;
cout<<"请选择需要入栈个数(最多为十个):"<<endl;
q: cin>>c;
if(c>stacksize)
{
cout<<"输入个数超过限额,请重新输入:";
goto q;
}
else
{
cout<<"请以此输入需要入栈的整数:"<<endl;
int A[stacksize];
int b;
for(b=0;b<c;b++)
{
cin>>A[b];
}
int a;
for(a=0;a<c;a++)
{
s.push(A[a]);
}
}
cout<<"栈顶元素为:";
if(s.gettop()==0)
cout<<"栈为空"<<endl;
else
cout<<s.gettop()<<endl;
int d;
cout<<"选择出栈次数:";
cin>>d;
for(int D=0;D<d;D++)
{
s.pop();
}
cout<<"执行"<<d<<"次出栈操作后";
cout<<endl;
cout<<"栈顶元素为:";
if(s.gettop()==0)
cout<<"栈为空"<<endl;
else
cout<<s.gettop()<<endl;
}