在实现循环队列之前,我来说一说其中关键的地方:
1.front和rear指针的指向 问题:rear指最后一个节点,front的指针一般来说,指向队列中第一个节点的前一个位置
2.对于基于第一种情况,队列所能够存的最多数据个数为SIZE-1((SIZE为队列的大小)
3.初始化时,front与rear都是赋初始值0.
4.判空的条件:front==rear,对于这一个的记忆,你可以想象一个含有数据的队列,其不断删除,最后front的指针将会指向rear所指向的位置
5.判满的条件:(rear+1)%SIZE==front由于front的指针指向第一个节点的前一个位置,rear指向最后一个节点,所以当rear的下一个位置是front的则代表队列满
头文件:
#ifndef RQUEUE_H
#define RQUEUE_H
const int SIZE = 10;
class RQueue{
private:
int front, rear;
int data[SIZE];
public:
RQueue();
~RQueue();
bool enQueue(const int &elem);
bool deQueue(int &elem);
bool getFront(int &elem);
bool getRear(int &elem);
bool isEmpty() const;
bool isFull()const;
int length() const;
void display()const;
};
实现文件:
#include<iostream>
#include"RQueue.h"
using std::cout;
using std::endl;
RQueue::RQueue(){
front = rear = 0;
}
RQueue::~RQueue(){
front = rear =0;
}
bool RQueue::enQueue(const int &elem){
if ((rear + 1) % SIZE == front) return false;
rear = (rear + 1) % SIZE;
*(data + rear) = elem;
return true;
}
bool RQueue::deQueue(int &elem){
if (rear == front) return false;
front = (front + 1) % SIZE;
elem = *(data + front);
return true;
}
bool RQueue::getFront(int &elem){
if (front == rear) return false;
int index = (front + 1) % SIZE;
elem = *(data + index);
return true;
}
bool RQueue::getRear(int &elem){
if (rear == front) return false;
elem = *(data + rear);
return true;
}
bool RQueue::isEmpty() const{
return (front == rear);
}
bool RQueue::isFull()const{
return ((rear + 1) % SIZE == front);
}
int RQueue::length() const{
return (rear - front + SIZE) % SIZE;
}
void RQueue::display()const{
if (rear == front){ cout << "空!" << endl; return; };
int start =( front + 1) % SIZE;
while (start != ((rear+1)%SIZE)){
cout << *(data + start) << endl;
start = (start + 1) % SIZE;
}
cout << "长度:" <<this->length()<< endl;
}
主函数:
#include<iostream>
#include"RQueue.h"
using namespace std;
int main(){
RQueue *queue = new RQueue;
int num;
for (int i = 0; i < 10; i++) queue->enQueue(i);
queue->display();
queue->deQueue(num);
queue->display();
while (!queue->isEmpty()) queue->deQueue(num);
queue->display();
delete queue;
system("pause");
return 0;
}