模拟实现stack(只能栈顶操作数据,后进先出)
#include <iostream>
using namespace std;
template<class T>
class Vector
{
public:
Vector()
:_pData(new T[3])
,_size(0)
,_capacity(3)
{}
Vector& operator =(const Vector v)
{
swap(*this, v);
return *this;
}
~Vector()
{
if(_pData != NULL)
{
delete[] _pData;
_pData = NULL;
}
}
void PushBack(const T& data)
{
Check_capacity();
_pData[_size++] = data;
}
void PopBack()
{
if(_size != 0)
_size--;
}
T& Back()
{
return _pData[_size-1];
}
const T& Back()const
{
return _pData[_size-1];
}
size_t Size()const
{
return _size;
}
bool Empty()const
{
return _size == 0;
}
private:
void Check_capacity()
{
if(_size >= _capacity)
{
T* newpData = new T[_size*2];
for(size_t i = 0; i < _size; i++)
{
newpData[i] = _pData[i];
}
delete[] _pData;
_pData = newpData;
_capacity = _size*2;
}
}
T* _pData;
size_t _size;
size_t _capacity;
};
template<class T, class Container = Vector<T> >
class Stack
{
public:
void Push(const T& x)
{
return _con.PushBack(x);
}
void Pop()
{
return _con.PopBack();
}
const T& Top()const
{
return _con.Back();
}
size_t Size()const
{
return _con.Size();
}
bool Empty()
{
return _con.Empty();
}
private:
Container _con;
};
int main()
{
Stack<int> s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
cout<<s1.Size()<<endl;
s1.Pop();
cout<<s1.Top()<<endl;
cout<<s1.Empty()<<endl;
Stack<int, Vector<int>> s2;
Stack<int, Vector<char>> s3;
return 0;
}
模拟实现queue(只能队列头部操作数据,先进先出)
#include <iostream>
#include <assert.h>
using namespace std;
template<class T>
class Vector
{
public:
Vector()
:_pData(new T[3])
,_size(0)
,_capacity(3)
{}
Vector& operator =(const Vector v)
{
swap(*this, v);
return *this;
}
~Vector()
{
if(_pData != NULL)
{
delete[] _pData;
_pData = NULL;
}
}
void PushFront(const T& data)
{
Check_capacity();
for(size_t i = _size; i > 0; i--)
{
_pData[i] = _pData[i-1];
}
_pData[0] = data;
_size++;
}
void PopFront()
{
assert(_size);
for(size_t i = 0; i < _size-1; i++)
{
_pData[i] = _pData[i+1];
}
_size--;
}
T& Front()
{
return _pData[0];
}
const T& Front()const
{
return _pData[0];
}
size_t Size()const
{
return _size;
}
bool Empty()const
{
return _size == 0;
}
private:
void Check_capacity()
{
if(_size >= _capacity)
{
T* newpData = new T[_size*2];
for(size_t i = 0; i < _size; i++)
{
newpData[i] = _pData[i];
}
delete[] _pData;
_pData = newpData;
_capacity = _size*2;
}
}
T* _pData;
size_t _size;
size_t _capacity;
};
template<class T, template<class> class Container = Vector>
class Queue
{
public:
void Push(const T& x)
{
return _con.PushFront(x);
}
void Pop()
{
return _con.PopFront();
}
const T& Head()
{
return _con.Front();
}
size_t Size()const
{
return _con.Size();
}
bool Empty()
{
return _con.Empty();
}
private:
Container<T> _con;
};
int main()
{
Queue<int> s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
cout<<s1.Size()<<endl;
s1.Pop();
cout<<s1.Head()<<endl;
cout<<s1.Empty()<<endl;
Queue<int, Vector> s2;
return 0;
}
stack和queue底层都使用的是vector,对其进行封装,空间分配是连续的