栈的类模板实现

#include <iostream>
#include <cstdlib>

using namespace std;

const int Size=5;
const int Increment=10;

//模板类
template<class T>
class Stack
{
public:
	Stack();                        //构造函数
	T Pop();						//出栈
	T GetTop();						//获得栈顶的元数
	bool Visit();					//遍历打印栈内元数
	bool IsFull();					//栈是否满
	bool Push(T e);					//入栈
	bool IsEmpty();					//是否为空
	~Stack();						//析构函数

private:
	int size;
	T* top;
	T* base;
};

template<class T>
Stack<T>::Stack()
{
	base=(T*)malloc(sizeof(T)*Size);
	if(!base)
	{
		cout << "内存分配失败" << endl;
		exit(OVERFLOW);
	}
	top=base;
	size=Size;
}

template<class T>
T Stack<T>:: Pop()
{
	if(top-base<=0)
	{
		cout << "栈内已经没有数据!" <<endl;
		exit(1);
	}
	return *(--top);
}

template<class T>
T Stack<T>:: GetTop()
{
	if(IsEmpty())
	{
		cout << "栈内已经没有数据!" <<endl;
		exit(1);
	}
	return *(top-1);
}

template<class T>
bool Stack<T>:: Visit()
{
	if(IsEmpty())
	{
		cout << "栈内已经没有数据!" <<endl;
		exit(1);
	}
	T* p=--top;

	cout << "元数出栈依次为:" <<endl;
	for(p;p>=base;p--)
	{
		cout << "  " << *(p);
	}
	cout << endl;
	return true;
}

template<class T>
bool Stack<T>:: IsFull()
{
	if(top-base==size)
		return true;
	else
		return false;
}

template<class T>
bool Stack<T>:: Push(T e)
{
	if(IsFull())
	{
		T* p=(T*)realloc(base,(size+Increment)*sizeof(T));
		if(!p)
		{
			cout << "内存分配失败" << endl;
			exit(OVERFLOW);
		}
		base=p;
		top=base+size;
		size+=Increment;
	}
	*(top++)=e;
	return true;
}


template<class T>
bool Stack<T>:: IsEmpty()
{
	if(top==base)
		return true;
	else
		return false;

}

template<class T>
Stack<T>:: ~Stack()
{
	delete [] base;
}

//测试代码
int main()
{
	int e=0;
	Stack<int> s;

	for(int i=1;i<50;i++)
		s.Push(i);
	e=s.Pop();

	cout<< e << "  " <<s.GetTop() <<endl;
	cout<< s.IsFull() << "  " <<s.IsEmpty() <<endl;

	s.Visit();

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值