欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

顺序队列的c++实现,顺序队列实现,顺序队列的初始化及对队列

来源: javaer 分享于  点击 31410 次 点评:226

顺序队列的c++实现,顺序队列实现,顺序队列的初始化及对队列


顺序队列的初始化及对队列的操作保存在queue.h中

#ifndef QUEUE_H#define QUEUE_Htemplate <class T>class Queue{public:     Queue(int  queuecapacity);     bool Isempty();     void Front();     void Rear();     void Push(T item);     void Pop();private:    T *queue;    int front;    int rear;    int capacity;};//利用构造函数初始化顺序队列template <class T>Queue<T>::Queue(int  queuecapacity){  if( queuecapacity<1)   {       throw "the capacity of queue must be >0";    }  else   {          queue=new T[queuecapacity];       capacity=queuecapacity;       front=rear=0;  //牺牲front这个位置,这个位置不放元素    }}//元素进队列template <class T>void Queue<T>::Push(T item){    if((rear+1)%capacity==front)    {    throw "the queue is full";    }    else    {          rear=(rear+1)%capacity;          queue[rear]=item;     }}//出列template <class T>void Queue<T>::Pop(){       if(Isempty()) throw "the queue is empty";    front=(front+1)%capacity;}//判断队列是否为空template <class T>inline bool Queue<T>::Isempty(){    return front==rear; }//队首元素template <class T>inline void Queue<T>::Front(){    if(!Isempty())    {     cout<<"队首元素为"<< queue[(front+1)%capacity]<<endl;    }    else    {     cout<< "the queue is empty"<<endl;    }}//队尾元素template <class T>inline void Queue<T>::Rear(){  if(!Isempty())    {    cout<<"队尾元素为"<< queue[rear]<<endl;    }    else    {     cout<< "the queue is empty"<<endl;    }}#endif    1    2    3    4    5    6    7    8    9    10    11    12    13    14    15    16    17    18    19    20    21    22    23    24    25    26    27    28    29    30    31    32    33    34    35    36    37    38    39    40    41    42    43    44    45    46    47    48    49    50    51    52    53    54    55    56    57    58    59    60    61    62    63    64    65    66    67    68    69    70    71    72    73    74    75    76    77    78    79    80    81    82    83    84    85    86    87    88    89    90    91    92    93    94主函数#include "queue.h"#include<iostream>using namespace std;int main(){ Queue<int> q(10); q.Push(1); q.Push(2); q.Push(3); q.Front(); q.Rear(); q.Pop(); q.Pop(); q.Pop(); q.Front(); q.Rear(); q.Push(4); q.Front(); q.Rear(); system("pause"); return 0;}
相关栏目:

用户点评