用c++实现顺序队列(用数组实现)

**********************************************queue.h*************************************

#ifndef SQUENTIALQUNUE_QUEUE_H
#define SQUENTIALQUNUE_QUEUE_H

#include <iostream>

using namespace std;

template <class T>
class queue
{
public:
    queue(int capacity);
    void push(const T& a);
    void pop();
    T Front();
    T Rear();
    bool isempty();
private:
    int front;
    int rear;
    int capacity;
    T* Queue;
};
template <class T>
queue<T>::queue(int capacity) {

    if (capacity<1) throw "queue capacity must be >0 ";
    this->capacity=capacity;
    Queue=new T[capacity];
    front=rear=0;
}

template <class T>
void queue<T>::push(const T& a) {

//    if (rear==capacity-1)
//    {
//        rear=0;
//    }
//    else                       等价于rear=(rear+1)%capacity;
//    {
//        rear++;
//    }
    rear=(rear+1)%capacity;
    if((rear+1)%capacity==front)//队列满了
    {
        T* newqueue=new T[2*capacity];//加倍
        //判断是否发生了回绕
        int start=(front+1)%capacity;
        if (start<2)//没有回转
        {
            copy(Queue+start,Queue+start+capacity-1,newqueue);
        }
        else //发生了回转  所以需要拷贝两次
        {
            copy(Queue+start,Queue+capacity,newqueue);
            copy(Queue,Queue+capacity-start,newqueue+capacity-start);
        }
        front=2*capacity-1;
        rear=capacity-2;
        capacity*=2;
        delete[] Queue;
        Queue=newqueue;
    }
    Queue[rear]=a;
}

template <class T>
void queue<T>::pop() {
    if (isempty()) throw "queue is empty .cannot be delete";
    front=(front+1)%capacity;
    Queue[front].~T();
}

template <class T>
T queue<T>::Front() {
    return Queue[front+1];
}
template <class T>
T queue<T>::Rear() {
    return Queue[rear];
}
template <class T>
bool queue<T>::isempty() {
    return rear==front;
}
#endif //SQUENTIALQUNUE_QUEUE_H

 

***************************************.cpp**************************

#include <iostream>

//先进先出 或者后进后出
//队首 队尾
//对列的操作

//1.push 2.pop 3.front 4.rear 5.isempty
#include "queue.h"
int main() {
    queue<int> q(12);
    q.push(5);
    q.push(9);
    q.push(11);
    q.pop();
    cout<<q.Rear()<<endl;
    cout<<q.Front()<<endl;

    cout<<"-----------------"<<endl;
    cout<<q.isempty()<<endl;

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值