数据结构:相互之间存在一种或多种特定关系的数据元素的集合。
首先,我们先学习队列:
队列(FIFO)属性:先进先出(First in first out),现实生活中常见的队列就是:排队买票,先到先买。
队列是可以放任何数据类型的,也就是说队列的结构基本上只有一种。不同的队列只是放的数据类型不一样而已。掌握一种,吃透,其他的也是很容易上手的。
队列分为:普通类型、环形两种。
#include<iostream>
#include<stdlib.h>
using namespace std;
/********************************/
/*实现环形队列 */
/********************************/
class MyQueue
{
public :
//注释部分为在C环境下队列的接口形式
MyQueue(int quequeCapacity); //InitQueue(Q)创建队列
virtual ~MyQueue(); //DestroyQueue(&Q)销毁队列
void ClearQueue(); //Clear(&Q)清空队列
bool QueueEmpty()const; //Queue(Q)判空
bool QueueFull()const; //判满
int QueueLength()const; //Queuelength(Q)队列长度
bool EnQueue(int element); //EnQueue(&Q,&element)新元素入队
bool DeQueue(int &element); //DeQueue(&Q,&element)首元素出队
void QueueTraverse(); //QueueTraverse(Q,visit())遍历队列
private:
int *m_pQueue; //队列数组指针
int m_iQueueLen; //队列元素个数
int m_iQueueCapacity; //队列数组容量
int m_iHead;
int m_iTail;
};
//队列构造函数(刚开始,首尾指向同一个地方)
MyQueue::MyQueue(int queueCapacity)
{
m_iQueueCapacity = queueCapacity;
m_iHead = 0;
m_iTail = 0;
m_pQueue = new int[m_iQueueCapacity];//因为这里只是简单学习一下队列的使用,所以并没有对申请的空间进行判空
}
//队列析构函数,因为类中函数有数组指针
MyQueue::~MyQueue()
{
delete[]m_pQueue;
m_pQueue = NULL;
}
//清空队列
void MyQueue::ClearQueue()
{
m_iHead = 0;
m_iTail = 0;
m_pQueue = NULL;
}
//因为不需对队列进行修改,所以此处加上const修饰
bool MyQueue::QueueEmpty()const
{
if (m_iQueueLen == 0)
{
return true;
}
else
{
return false;
}
//return m_iQueueLen == 0 ?true : false;
}
//判断是否满
bool MyQueue::QueueFull()const
{
if (m_iQueueCapacity <= m_iQueueLen)
{
return true;
}
else
{
return false;
}
}
//入队函数
bool MyQueue::EnQueue(int 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(int &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;
}
}
int MyQueue::QueueLength()const
{
return m_iQueueLen;
}
int main(void)
{
MyQueue *p = new MyQueue(4);
p->EnQueue(10);
p->EnQueue(15);
p->EnQueue(20);
p->EnQueue(25);
p->QueueTraverse();
cout << endl;
int e = 0;
p->DeQueue(e);
cout << e << endl;
int w = 0;
p->DeQueue(w);
cout << w << endl;
p->QueueTraverse();
delete p;
p = NULL;
system("pause");
return 0;
}
当然也可以用队列整合其他数据类型,比如:对象,也可以,我们只需把其他的接口 int 改为 类。
也可以用用模板进行任意类型数据的整合