Queue_head.h
#ifndef _Queue_head_H
#define _Queue_head_H
#include <iostream>
template <typename 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 <typename 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 <typename T>
inline bool Queue<T>::IsEmpty() const
{
return front == rear;
}
template <typename T>
void Queue<T>::Push(const T& item)
{
if((rear+1) % capacity == front) // 判断队列满了吗
{
// 加倍
T* newQueue = new T[2*capacity - 1];
int start = (front+1) % capacity;
if(start < 2) // 没有回绕
std::copy(queue+start, queue+start+capacity-1, newQueue);
else{
std::copy(queue+start, queue+capacity, newQueue);
std::copy(queue, queue+rear+1, newQueue+capacity-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; // 相当于if else 的作用
queue[rear] = item;
}
template <typename T>
inline T& Queue<T>::Front() const
{
if(IsEmpty()) throw "No front element";
return queue[(front+1) % capacity]; // 队首一直是空的
// 取余处理回绕
}
template <typename T>
inline T& Queue<T>::Rear() const
{
if(IsEmpty()) throw "No rear element";
return queue[rear];
}
template <typename T>
void Queue<T>::Pop() // 删除队首数据
{
if(IsEmpty()) throw "cannot delete";
front = (front + 1) % capacity; // 处理回绕
queue[front].~T();
}
#endif
main.cpp
/*
* author:起风了_Zoe
* date:2020.04.07
*/
#include <iostream>
#include "Queue_head.h"
using namespace std;
int main()
{
Queue<char> q(4);
q.Push('a');q.Push('b');q.Push('c');
cout << q.Front() << "|" << q.Rear() << endl;
q.Push('d');q.Push('e');q.Push('f');
q.Push('g');q.Push('h');q.Push('i');
cout << q.Front() << "|" << q.Rear() << endl;
cout << "OK!!!" <<endl;
return 0;
}