爱嘉牛LA

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
View Code
#ifndef QUEUE_H
#define QUEUE_H
#include <cassert>
//类模版的定义
template<class T,int SIZE=50>          //size是队列能容纳的个数
class Queue{
private:
    int front,rear,count;              //队头指针,队尾指针,元素个数
    T list[SIZE];                      //队列的元素数组
public:
    Queue();                          //构造函数,初始化队头指针,队尾指针,元素个数
    void insert(const T &item);       //心元素入队
    T remove();                       //元素出队
    void clear();                     //清空队列
    const T &getFront()const;         //访问队首元素

    //测试队列状态
    int getLength()const;            //求队列长度(元素个数)
    bool isEmpty()const;             //判断队列空否
    bool isFull()const;               //判断队列满否

};
//构造函数,初始化队头指针,队尾指针,元素个数
template<class T,int SIZE>
Queue<T,SIZE>::Queue():front(0),rear(0),count(0){}

template<class T,int SIZE>
void Queue<T,SIZE>::insert(const T &item){
    assert(count!=SIZE);            //判断队中元素是不是定义的最大数了
    count++;                        //元素加一
    list[rear]=item;
    rear=(rear+1)%SIZE;                   //队尾指针增1
}
template<class T,int SIZE>
T Queue<T,SIZE>::remove(){          //删除队首元素,并返回该元素的值(出队)
    assert(count!=0);
    int temp=front;                 //记录下原先的队首的指针
    count--;                        //元素个数自减一
    front=(front+1)%SIZE;
    return list[temp];
}
template<class T,int SIZE>
const T&Queue<T,SIZE>::getFront()const{//访问队列首元素,返回其值
    return list[front];
}
template<class T,int SIZE>
int Queue<T,SIZE>::getLength()const{//返回队列的元素个数
    return count;
}
template<class T,int SIZE>
bool Queue<T,SIZE>::isEmpty()const{//判断是否空
    return count==0;
}
template<class T,int SIZE>
bool Queue<T,SIZE>::isFull()const{//判断队列满否
    return count==SIZE;
}
template<class T,int SIZE>
void Queue<T,SIZE>::clear(){//清空队列
    count=0;
    front=0;
    rear=0;
}
#endif

 

posted on 2012-12-03 14:24  爱嘉牛LA  阅读(199)  评论(0编辑  收藏  举报