队列实现
queue.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"queue.h"
void QueueTest()
{
Queue<int> q;
q.Push(1);
q.Push(2);
q.Push(3);
q.Push(4);
q.Push(5);
while (!q.Empty())
{
cout << q.Front() << " ";
q.Pop();
}
cout << endl;
}
int main()
{
QueueTest();
getchar();
return 0;
}