您的位置:首页 > 其它

STL之顺序容器适配器(队列的循环数组实现)

2012-09-26 14:59 519 查看
队列的循环数组实现······如果按照Vector,或者List的基础上去做就不用担心队列会满····这是按照教材、《数据结构与算法分析》、《算法导论》的用数组实现的思想····比较简单······所以····所以就没有解释······

#include<iostream>
using namespace std;

template<typename Object>
class Queue
{
public:
enum { Capacity = 10, Pos = 0 };
Queue( )
{
init( );
}
~Queue( )
{
delete [ ] data;
}

int size( )
{
return theSize;
}

bool empty( )
{
return  size( ) == 0;
}

void push( const Object & x )
{
if( size() == 0)
{
theFront++;
data[ ++theBack ] = x;
++theSize;
}
else
{
++theBack;
if( theBack  == theCapacity )
{
theBack %= ( theCapacity - 1 );
}
data[ theBack ] = x;
++theSize;

if( size() == theCapacity )
{
cout << "队列已经满了!" << endl;
}
}
}

void pop( )
{
theFront++;
if( theFront == theCapacity )
{
theFront %= ( theCapacity - 1 );
}
--theSize;
}

Object front( )
{
return data[ theFront ];
}

Object back( )
{
return  data[ theBack ];
}

private:
Object * data;
int theSize;
int theCapacity;
int theFront;
int theBack;

void init( )
{
theSize = 0;
theCapacity = Capacity;
theFront = theBack = Pos - 1;
data = new Object[ theCapacity ];
}
};

int main( )
{
Queue<int> q1;
cout << q1.size() << endl;
bool flag = true;
char c;
int m;
while( flag )
{
cout << "输入一个数字,这个数字将会进入队列!" << endl;
cin >> m;
q1.push( m );
cout << "是否继续输入?如果是,请输入Y,否则输入N。" << endl;
cin >> c;
if( c == 'Y' )
flag = true;
else
flag = false;
}
cout << "输出队首!" << endl;
cout << q1.front() << endl;
cout << "输出队尾!" << endl;
cout << q1.back() << endl;
cout << "输出队列的数目!" << endl;
cout << q1.size() << endl;
q1.pop( );
cout << "经过pop函数的处理后!" << endl;
cout << "输出队首!" << endl;
cout << q1.front() << endl;
cout << "输出队尾!" << endl;
cout << q1.back() << endl;
cout << "输出队列的数目!" << endl;
cout << q1.size() << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: