头文件:
#ifndef seqstack_H
#define seqstack_H
const int stacksize=10;
class seqstack
{
public:
seqstack();
~seqstack(){}
void push(int x);//将x元素入栈
int pop();//将栈顶元素弹出
int gettop();//取栈顶元素(并不删除)
int empty();
private:
int data[stacksize];
int top;
};
#endif
子函数:
#include"seqstack.h"//引入类seqstack的声明
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];
}
int seqstack::empty()
{
if(top==-1) return 1;
else return 0;
}
主函数:
#include<iostream>//引入输入输出流
using namespace std;
#include"seqstack.h"
void main()
{
seqstack s;
if(s.empty())
cout<<"栈为空"<<endl;
else
cout<<"栈非空"<<endl;
cout<<"对15和10执行入栈操作"<<endl;
s.push(15);
s.push(10);
cout<<"栈顶元素为:"<<s.gettop()<<endl;
cout<<"执行一次出栈操作"<<s.pop()<<endl;
cout<<"栈顶元素为:"<<s.gettop()<<endl;
}