template
<
typename
T
>
class
Stack
{
public
:
Stack()
:_a(
NULL
)
, _size(0)
, _capacity(0)
{ }
void
Push(
const
T
&
x
)
//相当于数组的尾插
{
_CheckCapacity();
_a[_size++] =
x
;
}
void
Pop()
//移去栈顶元素,栈顶指向数组的最后一个数据
{
if
(_size != 0)
{
_size--;
}
}
T
& Top()
//返回栈顶元素,即数组的最后一个元素
{
return
_a[_size-1];
}
bool
Empty()
//如果栈为空,则返回true,否则,返回false
{
if
(_size == 0)
{
return
true
;
}
else
{
return
false
;
}
}
size_t
Size()
//返回栈中元素数目
{
return
_size;
}
void
_CheckCapacity()
{
if
(_size == _capacity)
{
T
* temp =
new
T
[_capacity * 2 + 3];
for
(
int
index = 0; index < _size; ++index)
{
temp[index] = _a[index];
}
delete
[] _a;
_a = temp;
_capacity = _capacity * 2 + 3;
}
}
protected
:
T
* _a;
size_t
_size;
size_t
_capacity;
};
int
main()
{
Stack
<
int
> s;
s.Push(3);
s.Push(2);
s.Push(1);
//s.Pop();
//s.Empty();
int
ret=s.Top();
cout << ret << endl;
system(
"pause"
);
return
0;
}