C++模板实现顺序栈

使用C++模板实现的顺序栈,实现功能:

  • 可以指定初始大小
  • 支持拷贝构造
  • 栈满自动扩容
  • 入栈和出栈
  • 动态内存管理
  • 能获取最大容量和元素数量
#include <iostream>
using namespace std;

//顺序栈
template <class T1>
class Stack
{
public:
	Stack(const int size)//初始化
	{
		StackSize = size;
		base = new T1[StackSize];
		top = base;
		if (base == nullptr)
		{
			throw "分配内存失败";
		}
	}
	Stack(const Stack& other)//拷贝构造函数
	{
		StackSize = other.StackSize;
		base = new T1[StackSize];
		top = base;
		if (base == nullptr)
		{
			throw "分配内存失败";
		}
	}

	void Push(const T1& e)//入栈
	{
		if (top - base == StackSize)//满栈扩容
		{	
			T1* tempbase = new T1[2 * StackSize];
			T1* temptop = tempbase;
			if (tempbase == nullptr)
			{
				throw "拓展内存失败";
			}
			for (int i = StackSize; i > 0; i--)
			{
				*temptop = *(top - i);
				temptop++;
			}
			delete[]base;
			base = tempbase;
			top = temptop;
			StackSize *= 2;
		}
		*top = e;
		top++;
	}
	
	void Pop()//出栈
	{
		if (base == top)
		{
			throw "栈为空";
		}
		top--;
	}
	T1& Top()//获取栈顶元素
	{
		if (base == top)
		{
			throw "栈为空";
		}
		return *(top - 1);
	}

	int Length()//获取元素数量
	{
		return top - base;
	}

	int Size()//获取栈的最大容量
	{
		return StackSize;
	}

	~Stack()
	{
		if (base != nullptr)
		{
			base = nullptr;
			top = nullptr;
			delete[]base;
		}
	}
private:
	int StackSize;
	T1* base = nullptr;//栈底指针
	T1* top = nullptr;//栈顶指针
};


int main()
{
    //测试
	Stack<int> stack(10);
	for (int i = 0; i < 100; i++)
	{
		stack.Push(i);
	}
	for (int i = 0; i < 100; i++)
	{
		cout<<stack.Top()<<",";
		stack.Pop();
	}
	cout << endl;

	cout << stack.Length() << endl;
	cout << stack.Size() << endl;

	system("pause");
	return 0;
}

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值