循環隊列

 

//-----------------------------------------------CirularQueue.h------------------------------------------------

template <class T>
class cirularQueue
{
private:
int maxSize;
int front;
int rear;
T *data;
public:
cirularQueue(int maxLength)
{
   maxSize=maxLength;
   cout<<"循環隊列的最大長度爲:"<<maxSize<<endl;
   front=rear=0;
   data=new T[maxLength];
}
~cirularQueue()
{
   front=rear=0;
   delete []data;
   cout<<"調用析構函數!"<<endl;
}
bool isFull()
{
   return (rear+1)%maxSize==front;
}
bool isEmpty()
{
   return front==rear;
}
bool push(T info)
{
   if(isFull())
   {
    cout<<"錯誤!隊列已滿!"<<endl;
    return false;
   }
   else
   {
    data[rear]=info;
    rear=(rear+1)%maxSize;
    return true;
   }
}
bool pop(T &info)
{
   if(isEmpty())
   {
    cout<<"錯誤!隊列爲空!"<<endl;
    return false;
   }
   else
   {
    info=data[front];
    front=(front+1)%maxSize;
    return true;
   }
}
bool getHead(T &info)
{
   if(isEmpty())
   {
    cout<<"錯誤!隊列爲空!"<<endl;
    return false;
   }
   else
   {
    info=data[front];
    return true;
   }
}
void print()
{
   if(isEmpty())
   {
    cout<<"隊列爲空,沒有數據可以輸出!"<<endl;
   }
   else
   {
    int i=front;
     while(i!=rear)
      {
       cout<<data[i]<<" ";
       i=(i+1)%maxSize;
      }
    cout<<endl;
   }
}
};

//-------------------------------------------------CirularQueue.cpp-----------------------------------------------------

// cirularQueue.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include "iostream"
#include "cirularQueue.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
//cout<<"請輸入需要初始化隊列的最大長度:";
const int maxLength=5;
//cin>>maxLength;
cirularQueue<char> myQueue(maxLength);

cout<<"請輸入需要實際需要初始化的數據個數(實際可輸入數據的最大數目爲隊列最大長度減1):";
int n;
cin>>n;
char info;
for(int i=0;i<n;i++)
{
   cout<<"請輸入第"<<i+1<<"個數據:";
        cin>>info;
   myQueue.push(info);
}
myQueue.print();
cout<<endl;

cout<<"請輸入需要入隊的數據值:";
cin>>info;
if(myQueue.push(info))
{
     myQueue.print();
}
cout<<endl;

cout<<"隊首出隊"<<endl;
if(myQueue.pop(info))
{
     cout<<"出隊的數據的值爲:"<<info<<endl;
     myQueue.print();
}
cout<<endl;

cout<<"返回隊首"<<endl;
if(myQueue.getHead(info))
{
     cout<<"隊首的數據值爲:"<<info<<endl;
     myQueue.print();
}
cout<<endl;

return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章