136-C++模板stack的实现

#include<stdlib.h>
template<class Type>
class Stack
{
	Type *data;
	int maxsize;
	int pos;
	bool IncSize()//扩容操作,判断是否扩容成功 
	{
		int total = maxsize * 2; 
		Type* newdata = (Type *)malloc(sizeof(Type)*total);
		if(newdata == NULL) return false;
		memmove(newdata,data,sizeof(Type)*maxsize); 
		free(data);
		data = newdata;
		return true;
	}
public:
	Stack(int sz = 10):maxsize(sz),pos(-1)//初始化栈 
	{
		data = (Type*)malloc(sizeof(Type)*maxsize);//申请空间 
	}
	~Stack()//析构函数 
	{
		if(data != NULL)
		{
			for(int i = 0;i<=pos;++i)
			{
				(data+i)->~Type();
			}
			free(data);//释放资源 
		}
		data = NULL;//释放后记得将指针置为空 
		maxsize = 0;
		pos = -1;
	}
	int size() const { return pos+1;}//获取大小 
	bool empty() const { return size() == 0;}//判空 
	bool full() const { return size() == maxsize;}//判满 
	bool push(const Type &x)//入栈并判断是否入栈成功 
	{
		if(full() && !IncSize())
		{
			return false;
		}
		pos+=1;
		data[pos] = x;
		return true;
	}
	Type & top() { return data[pos];}//获取栈顶元素的值(可修改) 
	const Type & top() const{ return data[pos];}//获取栈顶元素的值(不可修改) 
	void pop()//出栈 
	{
		if(!empty())//不为空 
		{
			(data + pos)->~Type();
			pos-=1;
		}
	}
}; 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林林林ZEYU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值