c++实现循环队列

#include <iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;
int len=10;// the len of the que
typedef struct que{
int *qbase;
int fr;
int tr;
}ques;
bool isempty(ques *ptr)
{
    if(ptr->fr==ptr->tr)
    {
        return true;
    }
    return false;

}
bool isfull(ques *ptr)
{
    if((ptr->tr+1)%len==ptr->fr)
    {
        return true;
    }
    return false;
}
void initque(ques *ptr)
{
  ptr->qbase=(int *)malloc(sizeof(int)*len);
  //不判断内存是否申请失败了哈。。。
  ptr->fr=ptr->tr=0;
}
void enque(ques *ptr,int val)
{
  if(isfull(ptr))
  {
      cout<<"满了,填不进去了"<<endl;
  }
  else{

    ptr->qbase[ptr->tr]=val;
    ptr->tr=(ptr->tr+1)%len;
    cout<<"en que ok"<<endl;
  }

}
void dque(ques *ptr)
{
    if(isempty(ptr))
    {
        cout<<"队列空了"<<endl;
    }
    else{
        ptr->qbase[ptr->fr]=0;
        ptr->fr=(ptr->fr+1)%len;
    }

}
void printque(ques *q)
{
    if(isempty(q))
    {
        cout<<"空队列"<<endl;
    }
    else{
        int i=q->fr;
        while(i!=q->tr)
        {
            cout<<q->qbase[i]<<"  "<<endl;
            i=(i+1)%len;
        }
    }
}
int main()
{
    ques q={NULL,0,0};//表示一个队列

    cout<<isfull(&q)<<endl;
    cout<<isempty(&q)<<endl;
    initque(&q);
    enque(&q,23);
    enque(&q,83);
    enque(&q,293);
    enque(&q,213);
    dque(&q);
    printque(&q);
    cout << "Hello world!" << endl;
    return 0;
}

 

posted on 2016-10-23 15:33  邗影  阅读(1458)  评论(0编辑  收藏  举报

导航