# 数据结构课后题目源码

循环队列采用一维数组作为它的存储表示，往往很难确定到底数组需要设置多少元素才够用，设置太多元素，可能造成浪费，设置太少元素，可能造成溢出，为此可以改写队列的插入和删除算法，自动根据需要调整队列的存储数组的大小。

（1）改写队列的插入函数，当对列满并需要插入新元素时将数组空间扩大一倍，使新元素得以插入。

（2）改写队列的删除函数，当队列元素少于数组空间的1/4时将数组空间自动缩减一半。

#ifndef CIRSQUEUE_H_
#define CIRSQUEUE_H_
#include <iostream>

using namespace std;

template<class T>
class CirsQueue{
private:
int front;
int rear;
T * elements;
int maxSize;
public:
CirsQueue(int sz = 10);
~CirsQueue();
void EnQueue(const T & x);
bool DeQueue(T & x);
void initiaQueue(int n);
};

template<class T>
CirsQueue<T>::CirsQueue(int sz)
{
maxSize = sz;
elements = new T[maxSize];
front = rear = 0;
}

template<class T>
CirsQueue<T>::~CirsQueue()
{
delete[] elements;
}

template<class T>
void CirsQueue<T>::EnQueue(const T & x)
{
if (rear % maxSize == front)
{
cout << "队列已满，进行扩容！" << endl;
T * temp = new T[maxSize * 2];
for (int i = 0; i < maxSize; i++)
{
temp[i] = elements[i];
}
delete[] elements;
elements = temp;
rear = (rear + 1) % (maxSize * 2);
elements[rear] = x;
cout << "新的队列已建好！" << endl;
}
else
{
elements[rear] = x;
rear = (rear + 1) % maxSize;

}
}

template<class T>
bool CirsQueue<T>::DeQueue(T & x)
{
if (front == rear)
{
cout << "队列为空！缩小队列空间为原来的1/2！" << endl;
T * temp = new T[maxSize / 2];
delete[] elements;
elements = temp;
cout << "队列已缩短为原来的1/2！" << endl;
return false;
}
else
{
x = elements[rear];
front = (front + 1) % maxSize;
if ((rear-front) < (maxSize / 4))
{
cout << "把原来的队列缩短为原来的1/2" << endl;
T * tem = new T[maxSize / 2];
for (int i = 0; i <= rear; i++)
{
tem[i] = elements[i];
}
delete[] elements;
elements = tem;
return true;
}
return true;
}
}

template<class T>
void CirsQueue<T>::initiaQueue(int n)
{
T value;
if (n > maxSize)
{
cout << "初始化时请勿超出容量" << endl;
}
else if (n == 0)
{
cout << "输入队列数不能为0" << endl;
}
else
{
for (int i = 0; i < n; i++)
{
cout << "请输入第" << i + 1 << "个值： ";
cin >> value;
elements[i] = value;
rear = (rear + 1) % maxSize;
}

cout << "队列初始化成功！共含有" << n << "个值在队列中！" << endl;
}
}
#endif
// ex3-24.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "cirsQueue.h"

int _tmain(int argc, _TCHAR* argv[])
{
int temp;
int temp2=2;
CirsQueue<int> a(12);
CirsQueue<int> b(5);
a.initiaQueue(2);
b.initiaQueue(5);
a.DeQueue(temp);
b.EnQueue(temp2);

system("pause");

return 0;
}