基本数据结构——队列(动态数组C++)

基本数据结构——队列(动态数组C++)

特点:先进先出、后进后出

队首front(为空,加一才是第一个数据)、队尾rear(指向数组的最后一个数据)

基本操作:

  • Push 给队尾添加数据
  • Pop 从队首删除数据
  • Front 查看队首的数据
  • Rear 查看队尾的数据
  • IsEmpty 判断是否为空
//建立头文件queue.h

#ifndef _QUEUE_H
#define _QUEUE_H
#include<math.h>
using namespace std;

template<class T>
class Queue {
public:
	Queue(int queueCapacity = 10);  //构造函数定义
	bool IsEmpty() const;  //判断是否为空
	T& Front() const; //查看队首的数据
	T& Rear() const;  //查看队尾的数据
	void Push(const T& item);  //给队尾添加数据
	void Pop(); //从队首删除数据
private:
	T* queue;
	int front;  //队首的索引
	int rear;  //队尾的索引
	int capacity;  //队列容量
};

template<class T>
Queue<T>::Queue(int queueCapacity) :capacity(queueCapacity) {
	if (capacity < 1) throw"Queue capacity must be > 0";
	queue = new T[capacity];  //创建动态数组
	front = rear = 0;
}

template<class T>
inline bool Queue<T>::IsEmpty() const {
	return front == rear;
}

template<class T>
void Queue<T>::Push(const T& item) {
	if ((rear + 1) % capacity == front) {	//判断队列是否满了,即队尾队首接在一起
		//加倍
		T* newQueue = new T[2 * capacity];
		//if((rear+1)%capacity==front)  //是否发生回绕
		int start = (front + 1) % capacity;
		if(start<2)  //没有回转,no wrap
			copy(queue+start,queue+start+capacity-1,newQueue);
		else {
			copy(queue + start, queue + capacity, newQueue);
			copy(queue, queue + rear - 1, newQueue - start);
		}
		front = 2 * capacity - 1;
		rear = capacity - 2;
		capacity *= 2;
		delete[] queue;
		queue = newQueue;
	}

	/*if (rear == capacity - 1) //判断队尾是否是最后一个
		rear = 0;
	else
		rear++;
	*/
	rear = (rear + 1) % capacity;
	queue[rear] = item;
}

template<class T>
inline T& Queue<T>::Front() const {
	if (IsEmpty()) throw"Queue is empty. No front element.";
		return queue[(front + 1) % capacity]; //队首指向为空,加一指向队首数据
}

template<class T>
inline T& Queue<T>::Rear() const {
	if (IsEmpty()) throw"Queue is empty. No rear element.";
		return queue[rear];
}

template<class T>
void Queue<T>::Pop() {
	if (IsEmpty()) throw"Queue is empty. Cannot delete.";
	front = (front + 1) % capacity;
	queue[front].~T();
}

#endif

建立main.cpp文件
#include <iostream>
#include "queue.h"
using namespace std;

int main()
{
    cout << "Test the queue!" << endl;
    Queue<char> q(5);  //不写参数默认为10个
    //Queue<int> q(8); 
    q.Push('A');
    q.Push('B');
    q.Push('C');
    cout << q.Front() << ", " << q.Rear() << endl;
    q.Push('D');
    q.Push('E');
    cout << q.Front() << ", " << q.Rear() << endl;
    //q.Pop();
    //cout << q.Front() << ", " << q.Rear() << endl;
    q.Push('F');
    cout << q.Front() << ", " << q.Rear() << endl;
    q.Push('G');
    cout << q.Front() << ", " << q.Rear() << endl;

    return 0;
}
发布了76 篇原创文章 · 获赞 30 · 访问量 5817

猜你喜欢

转载自blog.csdn.net/weixin_45926367/article/details/104896367
今日推荐