动态数组实现栈

 VS2005运行通过,如有问题,请各位大牛指正。

/*动态栈的条件
栈顶初始值: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、含默认参数的参数序列书写顺序:非默认参数 默认参数
*/


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值