#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;
}
栈的模拟实现
最新推荐文章于 2023-11-26 00:48:57 发布