加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

顺序队列的c++实现

发布时间:2020-12-15 03:23:17 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #ifndef QUEUE_H#define QUEUE_Htemplate class Tclass Queue{public: Queue(int queuecapacity); bool Isempty(); void Front(); void Rear(); void

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#ifndef QUEUE_H
#define QUEUE_H
template <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;
}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读