Stack的模拟实现
栈的特性:后进先出
接口一般有:
push();
pop();
size();
empty();
top();
#pragma once
#include <assert.h>
template<class T>
class Stack
{
public:
Stack()
:_a(NULL)
,_size(0)
,_capacity(0)
{}
~Stack()
{
delete[] _a;
_a = NULL;
_size = _capacity = 0;
}
Stack(const Stack<T>& s);
Stack<T>& operator=(const Stack<T>& s);
public:
void Push(const T& x)
{
_CheckCapacity();
_a[_size++] = x;
}
void Pop()
{
assert(_size);
--_size;
}
T& Top()
{
assert(_size > 0);
return _a[_size-1];
}
const T& Top() const
{
assert(_size > 0);
return _a[_size-1];
}
size_t Size()
{
return _size;
}
bool Empty()
{
return _size == 0;
}
protected:
void _CheckCapacity()
{
if (_size >= _capacity)
{
size_t newCapacity = _capacity*2 + 3;
T* tmp = new T[newCapacity];
if (_a)
{
for (size_t i = 0; i < _size; ++i)
{
tmp[i] = _a[i];
}
}
_capacity = newCapacity;
delete[] _a;
_a = tmp;
}
}
protected:
T* _a;
size_t _size;
size_t _capacity;
};