// DStack.cpp : 定义控制台应用程序的入口点。
//动态数组实现栈
#include "stdafx.h"
#include <iostream>
using namespace std;
const int DStackIncreMent = 20;
/*动态栈的条件
栈顶初始值:top=0;
栈顶:总是指向刚刚压入值的下一单元
栈空:top=0
栈满:top=Max (或者不存在栈满,可以继续申请空间)
入栈: data[top++] = NewItem;
出栈:newItem = data[--top];
*/
template<class Type>
class DStack
{
public:
DStack(int maxSize = 100);
DStack(const DStack<Type>& otherDStack);
~DStack();
DStack<Type> operator=(const DStack<Type>& otherDStack);
void initDStack();
bool isEmptyDStack()const;
bool IsFullDStack() const;
void destoryDStack();
void pop(Type& popdata);
void push(Type pushdata);
private:
Type *data;
int top;
int maxSize;
};
template<class Type>
DStack<Type>::DStack(int maxSize)
{
top = 0;
this->maxSize = maxSize;
data = new Type[maxSize];
}
template<class Type>
DStack<Type>::DStack(const DStack<Type>& otherDStack)
{
top = otherDStack.top;
maxSize = otherDStack.maxSize;
data = new Type[maxSize];
if (!otherDStack.isEmptyDStack())
{
memcpy(data,otherDStack.data,maxSize);
}
}
template<class Type>
DStack<Type>::~DStack()
{
if (data != NULL)
{
destoryDStack();
}
}
template<class Type>
DStack<Type> DStack<Type>::operator=(const DStack<Type>& otherDStack)
{
if (this!=&otherDStack)
{
if (!otherDStack.isEmptyDStack())
{
if (maxSize!=otherDStack.top)//被赋值的对象太小,重新申请
{
maxSize = otherDStack.maxSize;
delete[] data;
data = new Type[maxSize];
}
top = otherDStack.top;
memcpy(data,otherDStack.data,maxSize);
}
}
return *this;
}
template<class Type>
void DStack<Type>::initDStack()
{
top = 0;
}
template<class Type>
bool DStack<Type>::isEmptyDStack()const
{
if (top==0)
{
return true;
}
else
{
return false;
}
}
template<class Type>
bool DStack<Type>::IsFullDStack() const
{
if (top==maxSize)
{
return true;
}
else
{
return false;
}
}
template<class Type>
void DStack<Type>::destoryDStack()
{
top = 0;
delete[] data;
data = NULL;
}
template<class Type>
void DStack<Type>::pop(Type& popdata)
{
if (isEmptyDStack())
{
popdata = -1;
cout<<"栈空!"<<endl;
}
else
{
popdata = data[--top];
}
}
template<class Type>
void DStack<Type>::push(Type pushdata)
{
if (IsFullDStack())
{
maxSize = maxSize+DStackIncreMent; //增加空间
Type *newdata = new Type[maxSize];
memcpy(newdata,data,maxSize);
delete data;
data = newdata;
}
else
{
data[top++] = pushdata;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
DStack<int> s;
int a[4] = {3,4,5,6};
for (int i=0; i<4; i++)
{
s.push(a[i]);
}
for (int i=0; i<4; i++)
{
int data;
s.pop(data);
cout<<data<<" ";
}
cout<<endl;
system("pause");
return 0;
}
动态数组实现栈
最新推荐文章于 2022-11-05 22:25:46 发布