基于数组的循环队列的实现:
CycleQueueBaseArray.h:
#pragma once
template <class T>
class CycleQueueBaseArray {
private:
T *array;
int maxLength;
int head;
int tail;
public:
CycleQueueBaseArray();
CycleQueueBaseArray(int length);
bool offer(T value);
T poll();
T peek();
bool isEmpty();
bool isFull();
};
CycleQueueBaseArray.cpp:
#include"CycleQueueBaseArray.h"
template <class T> CycleQueueBaseArray<T>::CycleQueueBaseArray() {
array = new T[64];
maxLength = 64;
head = 0;
tail = 0;
}
template <class T> CycleQueueBaseArray<T>::CycleQueueBaseArray(int length) {
array = new T[length];
maxLength = length;
head = 0;
tail = 0;
}
template <class T> bool CycleQueueBaseArray<T>::offer(T value) {
if (!isFull()) {
array[tail] = value;
tail = (tail + 1) % maxLength;
return true;
}
else {
return false;
}
}
template <class T> T CycleQueueBaseArray<T>::poll() {
if (!isEmpty()) {
head = (head + 1) % maxLength;
return array[(head-1)%maxLength];
}
else {
return NULL;
}
}
template <class T> T CycleQueueBaseArray<T>::peek() {
if (!isEmpty()) {
return array[head];
}
else {
return NULL;
}
}
template <class T> bool CycleQueueBaseArray<T>::isEmpty() {
if (head == tail) {
return true;
}
else {
return false;
}
}
template <class T> bool CycleQueueBaseArray<T>::isFull() {
if (head == (tail + 1) % maxLength) {
return true;
}
else {
return false;
}
}
基于循环双指针链表的循环队列实现:
(循环双指针链表的实现在链表的实现)
CycleQueueBaseCycleLinkedList.h:
#pragma once
#include"CycleLinkedList.h"
template <class T>
class CycleQueueBaseCycleLinkedList {
private:
CycleLinkedList<T> list;
public:
CycleQueueBaseCycleLinkedList();
bool offer(T value);
T poll();
T peek();
bool isEmpty();
};
CycleQueueBaseCycleLinkedList.cpp:
#include"CycleQueueBaseCycleLinkedList.h"
template <class T> CycleQueueBaseCycleLinkedList<T>::CycleQueueBaseCycleLinkedList() {
}
template <class T> bool CycleQueueBaseCycleLinkedList<T>::offer(T value) {
return list.addAtTail(value);
}
template <class T> T CycleQueueBaseCycleLinkedList<T>::poll() {
if (isEmpty()) {
return NULL;
}
T value = list.getHead();
list.deleteHead();
return value;
}
template <class T> T CycleQueueBaseCycleLinkedList<T>::peek() {
if (isEmpty()) {
return NULL;
}
else {
return list.getHead();
}
}
template <class T> bool CycleQueueBaseCycleLinkedList<T>::isEmpty() {
return list.isEmpty();
}