对于数据结构真是无话可说,大一刚学完的,一学期没用,到再想用的时候啥都不会了,今天看了几道关于数据结构的简单操作的题都不会,果断把数据结构再看一遍,把慕课网(传送门在这 biu~)上面的视频又刷一遍,首先对队列这一部分先做一下总结(本次以循环队列为例进行说明)。
队列: 也被称为(FIFO)即 first in first out
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。
循环队列:
为充分利用向量空间,克服”假溢出”现象的方法是:将向量空间想象为一个首尾相接的圆环,并称这种向量为循环向量。存储在其中的队列称为循环队列(Circular Queue)。这种循环队列可以以单链表的方式来在实际编程应用中来实现。
首先关于循环队列,可以用下图来描述 如图【1-1】
对于循环队列有以下几种状态 如图
关于循环队列的基本信息弄明白后,我们接下来看关于代码的实现部分,
首先创建队列 MyQueue.h 文件:
#ifndef MYQUEUE_H
#define MYQUEUE_H
#define Status int
class MyQueue{
public:
MyQueue(int queueCapacity); //构造函数 初始化循环队列
virtual ~MyQueue(); //析构函数 销毁循环队列
void ClearQueue(); //清空队列中的元素
bool QueueEmpty() const; //判断队列是否为空 为空返回true
bool QueueFull() const; //判断队列是否满 队满返回true
int QueueLength() const; //返回该队列的长队
bool EnQueue(Status element); //入队操作
bool DeQueue(Status &element); //出队操作
void QueueTraverse(); //遍历队列
private:
int *m_pQueue; //创建队列所用的指针
int m_iQueueLen; //队列长队
int m_iQueueCapacity; //队列容量
int m_iHead; //队头
int m_iTail; //队尾
};
#endif
这个文件主要是对队列要实现操作所需要的变量和方法进行定义,然后在创建文件MyQueue.cpp 对次文件的方法进行实现:
#include "MyQueue.h"
#include <iostream>
using namespace std;
MyQueue::MyQueue(int queueCapacity){
m_iQueueCapacity = queueCapacity;
m_pQueue = new int[m_iQueueCapacity];
ClearQueue();
}
MyQueue::~MyQueue(){
delete []m_pQueue;
m_pQueue = NULL;
}
void MyQueue::ClearQueue(){
m_iHead = 0;
m_iTail = 0;
m_iQueueLen = 0;
}
bool MyQueue::QueueEmpty() const{
return m_iQueueLen == 0 ? true : false;
}
int MyQueue::QueueLength() const{
return m_iQueueLen;
}
bool MyQueue::QueueFull() const{
if(m_iQueueLen == m_iQueueCapacity){
return true;
}else{
return false;
}
}
bool MyQueue::EnQueue(Status element){
if(QueueFull()){
return false;
}else{
m_pQueue[m_iTail] = element;
m_iTail++;
m_iTail = m_iTail % m_iQueueCapacity;
m_iQueueLen++;
return true;
}
}
bool MyQueue::DeQueue(Status &element){
if(QueueEmpty()){
return false;
}else{
element = m_pQueue[m_iHead];
m_iHead++;
m_iHead = m_iHead % m_iQueueCapacity;
m_iQueueLen--;
return true;
}
}
void MyQueue::QueueTraverse(){
for(int i= m_iHead; i<m_iQueueLen + m_iHead; i++){
cout<< m_pQueue[i%m_iQueueCapacity]<<endl;
}
}
到这一步队列的基本操作差不多都实现了,接下来创建用来测试的主函数文件 mian.cpp 对创建的队列进行调用和测试,来检查代码的正确性:
#include <iostream>
#include <stdlib.h>
#include "MyQueue.h"
using namespace std;
int main(){
MyQueue *p = new MyQueue(4);
cout<<"入队"<<endl;
p->EnQueue(10);
p->EnQueue(12);
p->EnQueue(16);
p->EnQueue(18);
p->QueueTraverse();
cout<<"----------------"<<endl;
int e = 0;
p->DeQueue(e);
cout<<"出队元素:"<<e<<endl;
cout<<"----------------"<<endl;
cout<<"出队之后遍历"<<endl;
p->QueueTraverse();
cout<<"----------------"<<endl;
cout<<"清空队列"<<endl;
p->ClearQueue();
p->QueueTraverse();
delete p;
p = NULL;
// system("pause");
return 0;
}
最后运行结果如下图所示:
本例中只对简单的数据类型进行了操作演示,关于其他数据类型,大家可以尝试自行更改,希望与大家共同学习,一起进步!
共勉