封装顺序栈
#include <iostream>
#define MAXSIZE 10
using namespace std;
class My_stack
{
private:
int *ptr; //执行堆区空间
int top; //记录栈顶元素
public:
My_stack(int size,int top):ptr(new int[size]),top(top){}
int Getsize(); //有参构造,获取栈的大小
~My_stack();// 析构函数
bool Isempty();// 判空函数
bool Isfull();// 判满函数
int Push(int elem);// 入栈函数
void Pop();// 出栈函数
void Output();// 遍历栈
int Getelem();// 获取栈顶元素的引用
void BubbleSort();// 排序
};
//无参构造,获取栈的实际大小
int My_stack::Getsize()
{
return top-1;
}
//无参构造,析构函数
My_stack::~My_stack()
{
delete []ptr;
ptr=nullptr;
}
//无参构造,判空函数
bool My_stack::Isempty()
{
if(top==-1)
return true;
return false;
}
//无参构造,判满函数
bool My_stack::Isfull()
{
if(top==MAXSIZE-1)
return true;
return false;
}
//有参构造,入栈函数
int My_stack::Push(int elem)
{
if(Isfull())
return false;
++top;
*(ptr+top)=elem;
}
//无参构造,出栈函数
void My_stack::Pop()
{
if(Isempty())
return;
top--;
}
//无参构造,遍历栈
void My_stack::Output()
{
if(Isempty())
return;
for(int i=0;i<=top;i++)
{
cout<<*(ptr+i)<<" ";
}
}
//无参构造,获取栈顶元素的引用
int My_stack::Getelem()
{
return *(ptr+top);
}
//无参构造,排序
void My_stack::BubbleSort()
{
int tmp;
for(int i=0;i<top-1;i++)
{
for(int j=0;j<top-i-1;j++)
{
if(*(ptr+j)>*(ptr+j+1))
{
tmp=*(ptr+j);
*(ptr+j)=*(ptr+j+1);
*(ptr+j+1)=tmp;
}
}
}
Output();
}
int main()
{
My_stack stack(MAXSIZE,-1);
stack.Push(10);
stack.Push(5);
stack.Push(16);
stack.Push(20);
stack.Push(6);
stack.Pop();
stack.Output();
cout<<endl;
int a=stack.Getelem();
cout<<a<<endl;
stack.BubbleSort();
return 0;
}
思维导图