队列类

C++ code

#pragma once
#include "stdafx.h"

template <class T>
class CSqQueue //循环队列
{
public:
    CSqQueue()
    {
        MAX=100;
        init();
    }
    CSqQueue(int defMax)
    {
        MAX=defMax;
        init();
    }
    ~CSqQueue()
    {
        delete data;
    }
    int getLength()
    {
        return (rear-front+MAX)%MAX;
    }
    void EnQueue(T obj)
    {
        if((rear+1)%MAX==front) return;//队尾的下一位置在队头上
        data[rear]=obj;
        rear=(rear+1)%MAX;
    }
    T DeQueue()
    {
        if(front==rear) return NULL;
        T re=data[front];
        front=(front+1)%MAX;
        return re;
    }
    void display()
    {
        for(int i=front;(i)%MAX!=rear;i=(i+1)%MAX)    
        {
            printf("%d,",data[i]);
        }
        printf("
");
    }
protected:
private:
    int MAX;//最大长度
    int length;//当前长度
    T* data;//数据项
    int front;
    int rear;
    void init()
    {
        data=new T[MAX];
        front=0;
        rear=0;
    }
};

template <class T>
class CLkQueue //链队列
{
public:
    CLkQueue()
    {
        front=new  QNode;
        rear=front;
        front->next=NULL;
    }
    void EnQueue(T data)
    {
        QNode* tmp=new QNode;
        tmp->data=data;
        tmp->next=NULL;
        rear->next=tmp;
        rear=tmp;
    }
    T DeQueue()
    {
        if(isEmpty()) return NULL;
        QNode* tmp=front;
        T re=front->next->data;
        front=front->next;
        delete tmp;
        return re;
    }
    int getLength()
    {
        if(isEmpty()) return 0;
        int length=0;
        QNode* tmp=front;
        while(tmp->next)
        {
            length++;
            tmp=tmp->next;
        }
        return length;
    }
    bool isEmpty()
    {
        if(front==rear) return 1;
        return 0;
    }
    void display()
    {
        QNode* tmp=front->next;
        if(isEmpty()) return;
        do
        {
            printf("%d,",tmp->data);
            tmp=tmp->next;
        }while(tmp);
        printf("
");
    }
protected:
private:
    typedef struct QNode{
        T data;
        struct QNode * next;
    }QNode;
    QNode * front;
    QNode * rear;
};
原文地址:https://www.cnblogs.com/TQCAI/p/7606808.html