循环队列(附分析图)

循环队列

列表属性front始终指向第0个元素
循环队列(附分析图)_第1张图片
新添加元素:(动态数组容量不够的情况在下面)循环队列(附分析图)_第2张图片
删除元素:
循环队列(附分析图)_第3张图片添加元素:(实现循环的功能)循环队列(附分析图)_第4张图片

动态扩容:
循环队列(附分析图)_第5张图片

.h文件

class CircleQueue
{
     
private:
	int m_front;

	int m_size;//队列的大小
	int m_capaticy;
	int * m_element;

private:
	static const int DEFAULT_CAPACITY = 10;


private:
	void ensurecapaticy(int capatity);

public:
	CircleQueue();
	~CircleQueue();

	int size();

	bool isEmpty();

	void enQueue(int element);

	int deQueue();

	int front();

};

.cpp文件

#include "CircleQueue.h"



CircleQueue::CircleQueue()
{
     
	this->m_element = new int[DEFAULT_CAPACITY];
	//初始化
	this->m_size = 0;
	this->m_capaticy = DEFAULT_CAPACITY;
	this->m_front = 0;
}


CircleQueue::~CircleQueue()
{
     
	if (this->m_element != NULL)
	{
     
		delete this->m_element;
		this->m_element = NULL;
	}
}


int CircleQueue::size()
{
     
	return this->m_size;
}

bool CircleQueue::isEmpty()
{
     
	return this->m_size == 0;
}

void CircleQueue::enQueue(int element)
{
     
	ensurecapaticy(this->m_size + 1);
	this->m_element[(this->m_front + this->m_size)%this->m_capaticy] = element;
	this->m_size++;
}

int CircleQueue::deQueue()
{
     
	int frontelem = this->m_element[this->m_front];
	//delete (this->m_element + this->m_front);//???
	this->m_element[this->m_front] = NULL;
	this->m_front = (this->m_front+1)%this->m_capaticy;

	this->m_size--;
	return frontelem;
}


int CircleQueue::front()
{
     
	return this->m_element[this->m_front];
}

void CircleQueue::ensurecapaticy(int capatity)
{
     
	int oldCapacity = this->m_capaticy;
	if (oldCapacity >= capatity)
	{
     
		return;
	}

	//新容量
	int newCapacity = oldCapacity + (oldCapacity >> 1);
	int * newelement = new int[newCapacity];
	for (int i = 0; i < this->m_size; i++)
	{
     
		newelement[i] = this->m_element[(i+this->m_front)%this->m_capaticy];
	}
	delete this->m_element;
	this->m_element = newelement;
	//重置
	this->m_front = 0;
	this->m_capaticy = newCapacity;

	cout << "扩容了" << oldCapacity << "+" << newCapacity << endl;
}

谢谢大家的浏览。刚开始写博客,以后文档会越做越好的。加油

你可能感兴趣的:(算法,数据结构,队列,数据结构,c++,算法)