Queue-实现

1 篇文章 0 订阅
/* Queue.h */
#ifndef __QUEUE_H__
#define __QUEUE_H__
#include <iostream>
using namespace std;
extern "C"
{
    void exit(int);
}
const int nDefaultQueueSize = 50;
template <class T>
class Queue
{
private:
    T *qlist; //存放队列元素的指针(数组)
    int size; //队列大小(容量)
    int front; //队首位置
    int rear; //队尾位置(最后一个元素的下一位置)
    int count; //队列中元素的个数
public:
    //构造函数
    Queue(int initSize=nDefaultQueueSize)
    {
        if (initSize < 1)
            initSize = nDefaultQueueSize;
        qlist = new T[initSize];
        if (!qlist)
        {
            cerr << "存储空间分配失败,应用程序将终止!"<< endl;
            exit(1);
        }
        front = 0;
        rear = 0;
        count = 0;
        size = initSize;
    }
    //析构函数
    ~Queue()
    {
        if (qlist) delete [] qlist;
        front = 0;
        rear = 0;
        count = 0;
        size = 0;
    }
    //判断队列是否为空
    int QEmpty()
    {
        return front == rear;
        //return count == 0;
    }
    //判断队列是否已满
    int QFull()
    {
        return (rear+1) % size == front;
        //return count == size;
    }
    //队列长度
    int QLength()
    {
        return count;
        //return (rear - front + size) % size;
    }
    //队尾插入(追加)元素
    void QInsert(const T &item)
    {
        if (count == size)
        {
            cerr << "队列已满,无法再追加元素。"<< endl;

            return;
        }
        count ++;
        qlist[rear] = item;
        rear = (rear + 1) % size; //rear始终指向最后一个元素的下一个位置
    }
    //队首删除元素

    T QDelete( )
    {
        int pre_front=front;
        if (count > 0)
        {
            count --;
            front = (front + 1) % size; //front移向下一位置
        }
        else
            cerr << "队列已空,无法继续删除。" << endl;
        return qlist[pre_front];
    }
    //读取队首元素
    T QFront(T &data)
    {
        if (count > 0)
            data = qlist[front];
        else
            cerr << "队列为空,无法读取队首元素的值。" << endl;
        return data;
    }
    //清空队列
    void ClearQueue()
    {
        front = 0;
        rear = 0;
        count = 0;
    }
};
#endif __QUEUE_H__

        

// queue.cpp
#include "Queue.h"
#include<stdio.h>
int main()
{
    Queue<int> Q;
    int e,i;
    for(i=0; i<10; i++)
    {
        Q.QInsert(i);

    }
    Q.QInsert(256);
    cout << "Length : " << Q.QLength() << endl;
    cout << "front : " << Q.QFront(e) << endl;
    for(i=0;i<11;i++)
    {
        e=Q.QDelete();
        printf("%d   ",e);
    }



    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值