C++实现栈

栈只允许在末端进行插入和删除的线性表。栈具有后进先出的特性(LIFO,Last In First Out)。
#pragma once
#include<assert.h>

template<class T>
class Stack
{
public:
	Stack()
		:_array(NULL)
		, _capicity(0)
		, _topIndex(-1)
	{}
	~Stack()
	{
		delete[]_array;
		_capicity = 0;
		_topIndex = -1;
	}

	void Push(const T& x)//入栈
	{
		if (_topIndex + 1 == _capicity)
		{
			_capicity = 2 * _capicity + 3;
			T* tmp = new T[_capicity];
			if (tmp == NULL)
			{
				cout << " New Failed!" << endl;
				exit(-1);
			}
			memcpy(tmp,_array,sizeof(T)*(_topIndex+1));

			delete[] _array;
			_array = tmp;
		}
		_array[++_topIndex] = x;
	}
	void Pop()//出栈
	{
		assert(_topIndex > -1);
		--_topIndex;
	}
	bool Empty()
	{
		return _topIndex == -1;
	}
	bool Full() const
	{
		return _topIndex == _capicity - 1;
	}
	const T& Top()
	{
		return _array[_topIndex];
	}
	
private:
	T* _array;         //数据块
	size_t _capicity;  //容量
	int _topIndex;     //栈顶数据的下标
};


#include<iostream>
#include"Stack.hpp"
using namespace std;
void Test()
{
	Stack<int> s;
	s.Push(1);
	s.Push(2);
	s.Push(3);
	s.Push(4);
	s.Pop();
	while (!s.Empty())
	{
		cout << s.Top() << " ";
		s.Pop();
	}
	cout << endl;
}

int main()
{
	Test();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值