棧的模擬實現

#include <iostream>
using namespace std;
#include<assert.h>

template<class T>
class Stack
{
public:
	Stack()
		:_arr(NULL)
		,_size(0)
		, _capacity(0)
	{}
	void Push(const T& x)
	{
		_checkcapacity();
		_arr[_size] = x;
		_size++;
	}
	void Pop()
	{
		--_size;
	}
	T& Top()
	{
		assert(_arr);
		return _arr[Size()];
	}
	size_t Size()
	{
		return _Size();
	}
	bool Empty()
	{
		if (_Size())
		{
			return false;
		}
		return true;
	}
	~Stack()
	{
		delete[] _arr;
		_arr = NULL;
	}
protected:
	void _checkcapacity()
	{
		if (_size == _capacity)
		{
			size_t _newcapacity = 2 * _capacity + 1; 
			T* tmp = new T[_newcapacity];
			for (size_t i = 0; i < _size ;i++)
			{
				tmp[i] = _arr[i];
			}
			swap(tmp, _arr);
			_capacity = _newcapacity;
		}
		
	}
	size_t _Size()
	{
		return _size;
	}

private:
	T* _arr;
	size_t _size;
	size_t _capacity;
};

int main()
{
	Stack<int> a;
	
	cout << a.Empty() << endl;
	cout << a.Size() << endl;
	cout << a.Empty() << endl;
	//cout << a. << endl;
	
	a.Push(1);
	a.Push(2);
	a.Top();
	cout << a.Size() << endl;

	a.Push(3);
	a.Push(4);
	a.Push(5);
	cout << a.Size() << endl;

	a.Push(6);
	a.Push(7);
	a.Pop();
	a.Push(8);
	cout << a.Size() << endl;
	system("pause");
	return 0;
}

發佈了71 篇原創文章 · 獲贊 62 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章