栈数据结构的类;栈就是先入后出,
//栈模板类
#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;
template <class Type>
class stack_class
{
private:
int max_len;//空间大小
int len;//当前元素个数
Type *bottom;//头指针
Type *top;//栈顶的指针
public:
stack_class();
stack_class(stack_class<Type> & arg);
~stack_class();
bool IsEmpty();//是否为空,是返回1
void Push(const Type & arg);//栈插入元素
Type Pop();
};
int main()
{
stack_class<char> test;
cout<<"Isempty="<<test.IsEmpty()<<endl;
test.Push('a');
char c='b';
test.Push(c);
test.Push('x');
cout<<"pop="<<test.Pop()<<endl;
cout<<"Isempty="<<test.IsEmpty()<<endl;
cout<<"pop="<<test.Pop()<<endl;
cout<<"Isempty="<<test.IsEmpty()<<endl;
cout<<"pop="<<test.Pop()<<endl;
cout<<"Isempty="<<test.IsEmpty()<<endl;
return 0;
}
template <class Type>
stack_class<Type>::stack_class()
{
max_len = 1024;
len = 0;
bottom = new Type[len];
top = bottom;//默认指头指针
}
template <class Type>
stack_class<Type>::stack_class(stack_class<Type> & arg)
{
max_len = arg.max_len;
len = arg.len;
delete [] bottom;
bottom = new Type[max_len];
memcpy(bottom,arg.bottom,sizeof(Type)*len);
top = bottom+len-1;//一个元素的时候len=1,top指的是bottom
}
template <class Type>
stack_class<Type>::~stack_class()
{
max_len = 0;
len = 0;
delete [] bottom;
top = NULL;
}
template <class Type>
bool stack_class<Type>::IsEmpty()
{
if(len) return false;
else return true;
}
template <class Type>
void stack_class<Type>::Push(const Type & arg)
{
len++;
if(len>max_len)
{
max_len += 1024;
Type *tmp = new Type[max_len];
memcpy(tmp,bottom,sizeof(Type)*(len-1));
delete [] bottom;
bottom = tmp;
top = bottom+len-1;
*top = arg;
}
else
{
if(len==1)
{
*top = arg;
}
else
{
top = top+1;
*top = arg;
}
}
}
template <class Type>
Type stack_class<Type>::Pop()
{
assert(len!=0);
len--;
top = top-1;
return top[1];
}