栈 初学

来源:互联网 发布:linux 下载命令 编辑:程序博客网 时间:2024/06/04 19:11
#include<iostream>
using namespace std;
class stack
{
public:
stack(int size);//分配内存空间
~stack();       //回收栈的内存空间
bool stackempty(); //判断栈是否为空  空则返回true 非空false
bool stackfull();//判断栈是否为满   满则返回true 不满flase
void clearstack();//清空栈
int stacklength();//已有元素的个数
bool push(int elem);//入栈
bool pop(int &elem);//出栈
void stackper();//遍历栈
private:
int *buffer;//栈空间指针
int msize;//栈容量
int top;//栈顶/栈中的元素
};
stack::stack(int size)//构造函数
{
msize=size;
buffer=new int[msize];
top=0;
}


stack::~stack()//
{
delete[]buffer;
}


bool stack::stackempty()
{
if(0==top)
{
return true;
}
return false;
}


bool stack::stackfull()
{
if(top==msize)
{
return true;
}
return false;
}


void stack::clearstack()
{
top=0;
}


int stack::stacklength()
{
return top;

}


bool stack::push(int elem)
{
if(stackfull())
{
return false;
}
buffer[top]=elem;
top++;
return true;
}


bool stack::pop(int &elem)
{
if(stackempty())
{
return false;
}
top--;
elem=buffer[top];
return true;
}


void stack::stackper()
{

for(int i=0;i<top;i++)
{
cout<<buffer[i]<<" ";
}

}


int main(void)
{

int a,b;
cin>>a;
stack *p=new stack(a);
while(a--)
{
cin>>b;
p->push(b);
}
p->stackper();

}
原创粉丝点击