数组实现栈的顺序存储
#include<iostream>
#include<vector>
using namespace std;
const int max_size=100;
class seqstack
{
public:
seqstack();
~seqstack();
void push(int x);
int pop();
int gettop();
bool empty();
private:
int data[max_size];
int top;
};
seqstack::seqstack()
{
top=-1;//top指针初始在-1处
}
seqstack::~seqstack()
{
top=-1;
}
void seqstack::push(int x)
{
if(top==max_size) throw"溢出";
top++;
data[top]=x;
}
int seqstack::gettop()
{
return data[top];
}
bool seqstack::empty()
{
if(top==-1)
return true;
else return false;
}
int seqstack::pop()
{
if(top==-1) throw"栈空";
int x=data[top];
top--;
return x;
}
int main()
{
seqstack s;
s.push(8679);
int t=s.gettop();
cout<<"top:"<<t<<endl;
int p= s.pop();
cout<<"pop:"<<p<<endl;
bool is=s.empty();
cout<<is;
return 0;
}
一开始没写析构函数,运行不了。