c++动态数组实现栈。VS2005运行通过,如有问题,请各位大牛指正。
[cpp] view plaincopy
/*动态栈的条件
栈顶初始值:top=0;
栈顶:总是指向刚刚压入值的下一单元
栈空:top=0
栈满:top=Max (或者不存在栈满,可以继续申请空间)
入栈: data[top++] = NewItem;
出栈:newItem = data[--top];
*/
#include <iostream>
using namespace std;
const int StackIncreMent = 20;
template<class Type>
class Stack
{
private:
Type *data;
int top;
int maxSize;
public:
Stack(int maxSize = 100);
Stack(const Stack<Type>& otherStack);
~Stack();
Stack<Type> operator=(const Stack<Type>& otherStack);
void initStack();
bool isEmptyStack()const;
bool IsFullStack() const;
void destoryStack();
void pop(Type& data);
void push(Type data);
};
template<class Type>
Stack<Type>::Stack(int maxSize)
{
this->maxSize = maxSize;
data = new Type[maxSize];
top=0;
}
template<class Type>
Stack<Type>::Stack(const Stack<Type>& otherStack)//新建对象的数组没有空间,这时要申请空间
{
maxSize = otherStack.maxSize;
data = new Type[maxSize];
top = otherStack.top;
if (!otherStack.isEmptyStack())
{
memcpy(data,otherStack.data,maxSize);
}
}
template<class Type>
Stack<Type>::~Stack()
{
if (data!=NULL)
{
destoryStack();
}
}
template<class Type>
Stack<Type> Stack<Type>::operator=(const Stack<Type>& otherStack)
{
if (this != &otherStack)
{
if (!otherStack.isEmptyStack())
{
if (maxSize != otherStack.top) //要被赋值的对象太小,要重新申请
{
maxSize = otherStack.maxSize;
delete[] data;
data = new Type[maxSize];
}
top = otherStack.top;
memcpy(data,otherStack.data,maxSize);
}
}
return *this;
}
template<class Type>
void Stack<Type>::initStack()
{
top=0;
}
template<class Type>
bool Stack<Type>::isEmptyStack()const
{
return (top==0);
}
template<class Type>
bool Stack<Type>::IsFullStack()const
{
return (top==maxSize);//top表示指针位置,最大为Max-1
}
template<class Type>
void Stack<Type>::destoryStack()
{
top=0;
delete[] data;
data = NULL;
}
template<class Type>
void Stack<Type>::pop(Type& NewItem)
{
if (isEmptyStack())
{
NewItem = -1;
cout<<”栈空”<<endl;
}
else
{
NewItem = data[--top];
}
}
template<class Type>
void Stack<Type>::push(Type NewItem)
{
if (IsFullStack())
{
maxSize = StackIncreMent+maxSize;
Type* newData = new Type[maxSize];
memcpy(newData,data,maxSize);
delete data;
data = newData;
}
data[top++]= NewItem;
}
int main()
{
Stack<int> s;
int a[4]={1,2,3,4};
for (int i=0;i<4;i++)
{
s.push(a[i]);
}
Stack<int> s1= s;
for (int i=0;i<4;i++)
{
int temp;
s1.pop(temp);
cout<<temp<<endl;
}
system(“pause”);
return 0;
}
/*错误的地方:
1、类中定义的时候写: Stack(int maxSize = 100); 类外写的时候应为: Stack(int maxSize); //不能加默认参数
2、含默认参数的参数序列书写顺序:非默认参数 默认参数
*/