|
20鱼币
本帖最后由 Sj中国智造 于 2018-4-24 10:13 编辑
- /*-----------------------------------------------
- 循环队列(C++实现代码)
- -------------------------------------------------*/
- #include <iostream>
- #define MAX_SIZE 1025
- #define YES 1
- #define NO -1
- #define OK 2
- #define ERROR -2
- using namespace std;
- template<class T>
- class CIRQUEUE
- {
- public:
- CIRQUEUE();//申请一块内存
- ~CIRQUEUE();//释放一块内存
- int QueueIn(T data);//入队
- T QueueOut();//出队
- private:
- int front;//前指针
- int rear;//尾指针
- T *cirqueue;//指向分配的内存空间的首地址
- };
- //构造函数定义
- template<class T>
- CIRQUEUE<T>::CIRQUEUE()
- {
- front = rear = 0;//初始化为0
- this->cirqueue = new T[MAX_SIZE];//开辟数据为T的MAX_SIZE大小的内存空间
- if (this->cirqueue == NULL)
- {
- cout <<"分配内存失败啦~~"<<endl;
- }
- }
- //析构函数的定义
- template<class T>
- CIRQUEUE<T>::~CIRQUEUE()
- {
- if (this->cirqueue!=NULL)
- {
- delete[] this->cirqueue;
- }
- }
- //入队函数定义
- template<class T>
- int CIRQUEUE<T>::QueueIn(T data)
- {
- if ((rear+1)%MAX_SIZE==front)
- {
- cout <<"对不起,队列已满!"<<endl;
- return ERROR;
- }
- else
- {
- rear = (rear+1)%MAX_SIZE;
- this->cirqueue[rear] = data;//入队
- return OK;//成功
- }
- }
- //出队函数定义
- template<class T>
- T CIRQUEUE<T>::QueueOut()
- {
- if ((front+1)%MAX_SIZE>rear)
- {
- cout <<"队列已空!"<<endl;
- exit(-1);//错误退出
- }
- else
- {
- T data = this->cirqueue[front+1];//出队
- front = (front+1)%MAX_SIZE;
- return data;
- }
- }
- int main()
- {
- CIRQUEUE<char> cirqu;
- cirqu.QueueIn('a');
- cirqu.QueueIn('b');
- cirqu.QueueIn('c');
- cout <<cirqu.QueueOut()<<cirqu.QueueOut()<<cirqu.QueueOut()<<endl;
- return 0;
- }
复制代码 为什么我只是把代码合起来输出,两个结果会不一样?详细见图 |
-
-
|