C++数据结构--循环队列的实现

1.循环队列模型与数组视图的对照
 






2.实现代码:
  const int MAX=3; //循环队列的固定长度 


template<typename T>
class myQue
{
private:
T que[MAX];
size_t front_index; //队首下标 
size_t back_index;  //队尾下标 
size_t length;      //队列长度 
public:
myQue():front_index(0),back_index(0),length(0) //初始化队列 
{
}

void pop()   //岀队 
{
if(empty())
{
cerr<<"error,the queue is empty."<<endl;
return;
}
que[front_index]=T(); //把队首元素置空 
front_index=(front_index+1)%MAX ; //计算队首下标的位置 
length--; 
 
}

void push(const T& val)  //入队 
{
if(full())
{
cerr<<"error,the queue is full."<<endl;
return;
}
que[back_index]=val;
back_index=(back_index+1)%MAX ; //计算队尾下标的位置 
length++;
}

T& front() //返回队首元素 
{
return que[front_index];
}

size_t size() //返回队列大小 
{
return length;;
}

bool empty()  //判断队列是否为空 
{
return length==0;
}

bool full()  //判断队列是否为满
{
return length==MAX; 


};


template<typename T>
//打印队列所有元素
void print(myQue<T> mq)
{
while(!mq.empty())
{
cout<<mq.front()<<ends;
mq.pop();
}
}


int main()
{
  myQue<int> mq;
  mq.pop(); //error,the queue is empty.
  mq.push(1);
  mq.push(2);
  mq.push(3);
  mq.push(4); //error,the queue is full.
  cout<<mq.size()<<endl; //3
  print(mq); //1 2 3
  cout<<endl<<endl;
  
  mq.pop();
  cout<<mq.size()<<endl; //2
  mq.push(4);
  print(mq); //2 3 4
    
}


运行结果:



另附队列的设配器类

template<typename T>
class myQue
{
private:
list<T> que;
public:
void pop()
{
que.pop_front();
}

void push(T val)
{
que.push_back(val);
}

T& front()
{
return que.front();
}

size_t size()
{
return que.size();
}

bool empty()
{
return que.empty();
}

};


template<typename T>
void print(myQue<T> mq)
{
while(!mq.empty())
{
cout<<mq.front()<<ends;
mq.pop();
}
}


int main()
{
  myQue<int> mq;
  mq.push(1);
  mq.push(2);
  mq.push(3);
  cout<<mq.size()<<endl;
//3
  print(mq); //1 2 3
  cout<<endl;
  
  mq.pop();
  cout<<mq.size()<<endl; //2
  print(mq); //2 3
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值