您的位置:首页 > 编程语言 > C语言/C++

C++中 栈的简单封装

2014-08-20 13:06 260 查看
/*******************
*      Stack	   *
* *****************/
#include <iostream>

using namespace std;

/***************************定义***************************************/
class Stack
{
public:
Stack(int capacity = 5);
virtual ~Stack();

bool push(int v);//返回是否入栈成功
bool pop(int *p = NULL);//返回出栈是否成功,成功则返回p [变相返回]

bool empty();//判断是否空栈
bool full();//判断是否栈满
private:
int * pdata;//存放数据
int capacity;//定义栈大小
int top;
};

/***************************构造函数************************************/
Stack::Stack(int capacity)
{
this->capacity = capacity;
pdata = new int[capacity];//不需要*sizeof[int]
top = 0;
}

/***************************析构函数************************************/
Stack::~Stack()
{
if(NULL!=pdata)
{
delete [] pdata;
}
pdata = NULL;
}

/***************************进栈函数************************************/
bool Stack::push(int v)
{
if(full())//stack is full
{
cerr<<"stack is full."<<endl;
return false;
}
cout<<"Stack push "<<v<<endl;
pdata[top++] = v;//简化
}

/***************************出栈函数************************************/
bool Stack::pop(int * p)
{
if(top <= 0)//if(empty())
{
cerr<<"stack is empty."<<endl;
return false;
}
if(NULL!=p)
{
*p = pdata[top-1];
}
cout<<"stack pop "<<pdata[top-1]<<endl;
top--;
return true;
}

/***************************判空函数************************************/
bool Stack::empty()
{
if(top<=0)
{
return true;
}
return false;
}

/***************************判满函数************************************/
bool Stack::full()
{
if(top>=capacity)
{
return true;
}
return false;
}

/***************************测试函数************************************/
int main(int argc,char **argv)
{
Stack s;
int i = 0;

s.push(1);
s.push(2);
s.pop();
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.push(7);

cout<<endl<<endl;
for(;i<7;i++)
{
s.pop();
}

return 0;
}


本文出自 “咙叮咚员外” 博客,请务必保留此出处http://lddyw.blog.51cto.com/4151746/1542462
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: