Implementation of 136-C++ template 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;
		}
	}
}; 

Guess you like

Origin blog.csdn.net/LINZEYU666/article/details/112726713