#include <iostream>
#include <string>
#include <cassert>
using namespace std;
/*用数组实现循环队列
(1)、设一标志位以区别队列是“空”还是“满”
(2)、少用一空间,约定“队列头指针在队尾指针的下一位置”上作为队列呈“满”状态的标志
*/
template <typename T>
class MyDeque
{
public:
MyDeque(int n= 10);//构造函数
bool EnterQueue(T element);//向队列插入元素
bool DeleteQueue(int &element);//从队列弹出元素
int QueueLength();;//返回队列的长度
private:
int front; //对头指针
int rear; //队尾指针
T *base; //动态分配的内存指针
int maxsize; //最大队列长度
};
template <typename T>
MyDeque<T>::MyDeque(int n)
{
base = (T*)new T[n];
assert(base != NULL);
memset(base, 0, n);
front = rear = 0; //队头和队尾指针分别指向地一个元素
maxsize = n;
}
template <typename T>
bool MyDeque<T>::EnterQueue(T element)
{
if ((rear + 1) % maxsize == front) //判断队列是否满
{
return false;
}
else
{
base[rear] = element;
rear = (rear+1) % maxsize;
return true;
}
}
template <typename T>
bool MyDeque<T>::DeleteQueue(int &element)
{
if (front == rear)//判断队列是否为空
{
return false;
}
else
{
element = base[front];
base[front] = 0;
front = (front + 1) % maxsize;
return true;
}
}
template <typename T>
int MyDeque<T>::QueueLength()
{
return (rear - front + maxsize) % maxsize;
}
int main()
{
MyDeque<int> my(10);
int i;
for (i=0 ;i<5; i++)
{
my.EnterQueue(i+1);
}
cout<<"队列长度:"<<my.QueueLength()<<endl;
int element;
for (i=0; i<5; i++)
{
my.DeleteQueue(element);
printf("第%d个元素为%d/n", i+1, element);
}
cout<<"队列长度:"<<my.QueueLength()<<endl;
}
#include <string>
#include <cassert>
using namespace std;
/*用数组实现循环队列
(1)、设一标志位以区别队列是“空”还是“满”
(2)、少用一空间,约定“队列头指针在队尾指针的下一位置”上作为队列呈“满”状态的标志
*/
template <typename T>
class MyDeque
{
public:
MyDeque(int n= 10);//构造函数
bool EnterQueue(T element);//向队列插入元素
bool DeleteQueue(int &element);//从队列弹出元素
int QueueLength();;//返回队列的长度
private:
int front; //对头指针
int rear; //队尾指针
T *base; //动态分配的内存指针
int maxsize; //最大队列长度
};
template <typename T>
MyDeque<T>::MyDeque(int n)
{
base = (T*)new T[n];
assert(base != NULL);
memset(base, 0, n);
front = rear = 0; //队头和队尾指针分别指向地一个元素
maxsize = n;
}
template <typename T>
bool MyDeque<T>::EnterQueue(T element)
{
if ((rear + 1) % maxsize == front) //判断队列是否满
{
return false;
}
else
{
base[rear] = element;
rear = (rear+1) % maxsize;
return true;
}
}
template <typename T>
bool MyDeque<T>::DeleteQueue(int &element)
{
if (front == rear)//判断队列是否为空
{
return false;
}
else
{
element = base[front];
base[front] = 0;
front = (front + 1) % maxsize;
return true;
}
}
template <typename T>
int MyDeque<T>::QueueLength()
{
return (rear - front + maxsize) % maxsize;
}
int main()
{
MyDeque<int> my(10);
int i;
for (i=0 ;i<5; i++)
{
my.EnterQueue(i+1);
}
cout<<"队列长度:"<<my.QueueLength()<<endl;
int element;
for (i=0; i<5; i++)
{
my.DeleteQueue(element);
printf("第%d个元素为%d/n", i+1, element);
}
cout<<"队列长度:"<<my.QueueLength()<<endl;
}