栈实现
stack.h
//stack后进先出
#include<assert.h>
template<class T>
class Stack
{
public:
Stack()
:_pdata(NULL)
, _size(0)
, _capacity(0)
{}
~Stack()
{
delete[] _pdata;
_pdata = NULL;
_capacity = 0;
_size = 0;
}
void Push(const T& data)
{
CheckCapacity();
_pdata[_size++] = data;
}
void Pop()
{
if (_size != 0)
_size--;
}
T& top()
{
assert(_size);
return _pdata[_size-1];
}
bool Empty()const
{
if (_size == 0)
return true;
else
return false;
}
protected:
void CheckCapacity()
{
if (_size >= _capacity)
{
T *pcur = _pdata;
int NewCapacity = 2 * _capacity + 3;
_pdata = new T[NewCapacity];
for (int idx = 0; idx < _size; ++idx)
{
_pdata[idx] = pcur[idx];
}
delete[] pcur;
_capacity = NewCapacity;
}
}
protected:
T* _pdata;
int _size;
int _capacity;
};
测试部分:
test.cpp
#include<iostream>
using namespace std;
#include "stack.h"
void StackTest()
{
Stack<int> s;
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
s.Push(5);
while (!s.Empty())
{
cout << s.top() << " ";
s.Pop();
}
cout << endl;
}
int main()
{
StackTest();
getchar();
return 0;
}