我正在为一堂课做作业。我们必须实现基于数组的循环队列。我无法确定用于确定队列是否已满和空的算法。下面是我正在使用的C ++源文件:
#include <iostream>
#include <assert.h>
#include "circularQueue.h"
using namespace std;
template <class Type>
circularQueue<Type>::circularQueue(const int & capacity) {
assert (capacity >= 0);
this-> capacity = capacity;
front = 0;
rear = capacity-1;
array = new Type[capacity];
}
template <class Type>
circularQueue<Type>::~circularQueue() {
delete [] array;
}
template <class Type>
void circularQueue<Type>::add(Type value){
if (!isFull())
{
rear = (rear + 1) % capacity;
array[rear] = value;
}
else
{
cout << "The queue is full, cannot add value." << endl;
}
}
template <class Type>
void circularQueue<Type>::remove(){
if(!isEmpty())
{
front = (front + 1) % capacity;
}
else
{
cout << "Cannot delete from and empty queue." << endl;
}
}
template <class Type>
Type circularQueue<Type>::getFront() {
return array[front];
}
template <class Type>
Type circularQueue<Type>::getRear() {
return array[rear];
}
template <class Type>
int circularQueue<Type>::size() {
int size;
if (front > rear)
{
size = (capacity + rear) - front;
}
else
{
size = rear - front;
}
return size;
}
template <class Type>
bool circularQueue<Type>::isEmpty() {
bool empty = false;
if (front == rear) //if the front and rear are not pointing to the same index, its not full
{
empty = true;
}
return empty;
}
template <class Type>
bool circularQueue<Type>::isFull(){
bool full = true;
if (size() != capacity) // if size = capacity, queue is full;
{
full = false;
}
return full;
}
/* Test Procedure */
int main() {
circularQueue<int> queue(3); //create a queue that can hold 3 items(int)
queue.add(1); //add the value 1 to the queue [1]
queue.add(2); //add the value 2 to the queue [2, 1]
queue.add(3); //add the value 3 to the queue [3, 2, 1]
queue.add(4); // shouldn't work capacity is 3 trying to store 4 values
queue.remove(); //remove the element at the front[3, 2] front should point to 2
cout << "The front is: " << queue.getFront() << endl;
cout << "The rear is: " << queue.getRear() << endl;
cout << "The number of elements in the queue is: " << queue.size() << endl;
}
当我运行程序时,会产生以下输出:
无法从空队列中删除。
前面是:4
后部是:4
队列中的元素数量为:0
这让我相信我的isFull()isEmpty()和我的add()和remove()函数的逻辑都有错误。