循环队列实现

在实现循环队列之前,我来说一说其中关键的地方:

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值