class stack //定义栈这个类
{
public:
stack(int n); //构造函数
~stack(); //析构函数
bool isempty();//判断栈是否为空
bool isfull();//判断栈是否为满
void push(int e);//入栈函数
int gettop(); //得到栈顶元素
void pop(); //出栈函数
private:
int *elemarray; //定义数组
int top; //定义top作为栈顶的指针作用,指向栈顶we
int capicity;
};
#include"stack.h" //用""表示从本文件开始搜索,可以试试用<>的效果
#include<iostream>
using namespace std;
stack::stack(int n) //构造函数,初始化变量,给数组动态分配空间
{
capicity=n;
top=0;
elemarray=new int [capicity];
}
stack::~stack() //析构函数,收回动态分配空间
{
delete []elemarray;
}
bool stack::isempty()//判空函数
{
if (top ==0)
return true;
else return false;
}
bool stack::isfull()//判满函数
{
if(top==(capicity-1))
return true;
else
return false;
}
int stack::gettop() //输出栈顶的元素
{
cout<<"栈顶的元素是"<<elemarray[top]<<endl;
}
void stack::push(int e)//将元素入栈
{
if (top==capicity-1)
cout<<"Stack is full"<<endl;
else
elemarray[++top]=e;
}
void stack::pop() //将栈顶元素出栈
{
if (top==0)
cout<<"EMPTY STACK"<<endl;
else
top--;
}
#include"stack.h"
#include<iostream>
using namespace std;
int main()
{
//主函数,根据要求自行编写代码
return 0;
}
初学者写的不好见笑了,欢迎各位大佬前来指点,感激不尽!
更多推荐
栈(C++,数组实现,适合初学者)
发布评论