生活随笔
收集整理的這篇文章主要介紹了
环形队列的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vs2013下編寫的項目工程見 我的 github: https://github.com/excelentone/DataStruct
CircleQueue.h
#include<iostream>
using namespace std;
template<
class T>
class Queue
{
public:Queue(size_t size =
0) :_capacity(size),_head(
0),_rear(
0),_pBuf(
new T[size]),_QueueLen(
0){}Queue(
const Queue &q){_pBuf =
new T[q._capacity];
for (size_t i =
0; i < q._capacity; i++){_pBuf[i] = q._pBuf[i];}_capacity = q._capacity;_QueueLen = q._QueueLen;_rear = q._rear;_head = q._head;}Queue &
operator=(
const Queue &q){
if (
this != &q){
delete[]_pBuf;_pBuf =
new T[q._capacity];
for (size_t i =
0; i < q._capacity; i++){_pBuf[i] = q._pBuf[i];}_QueueLen = q._QueueLen;_capacity = q._capacity;_rear = q._rear;_head = q._head;}
return *
this;}
bool QueueFull(){
return _QueueLen == _capacity;}
void Enqueue(
const T data){
if (!QueueFull()){_pBuf[_rear] = data;_rear = (_rear +
1) % _capacity;_QueueLen++;}
else{
cout <<
"?óáDò??ú" << endl;}}
bool QueueEmpty(){
return _QueueLen ==
0;}
void Dequeue(){
if (!QueueEmpty()){_head = (_head +
1) % _capacity;_QueueLen--;}}
friend ostream&
operator<<(ostream &os,
const Queue &q){
for (size_t i = q._head; i < q._head + q._QueueLen; i++){os << q._pBuf[i%q._capacity] <<
" ";}
return os;}~Queue(){
if (NULL != _pBuf){
delete[]_pBuf;}}
private:T *_pBuf;size_t _capacity;size_t _QueueLen;size_t _head;size_t _rear;
};
test.cpp
#include"circleQueue.h"void test()
{
Queue<int
> *p
= new Queue<int
>(
4);p
->Enqueue(
5);p
->Enqueue(
6);p
->Enqueue(
7);p
->Enqueue(
8);p
->Enqueue(
9);cout
<< *p
<< endl;
Queue<int
> a(
10);a
.Enqueue(
1);a
.Enqueue(
2);a
.Enqueue(
3);a
.Enqueue(
4);cout
<< a
<< endl;
Queue<int
> b(a);cout
<< b
<< endl;
Queue<int
> c(
3);c
= a;cout
<< c
<< endl;
}
int main()
{test();system(
"pause");
}
轉載于:https://www.cnblogs.com/readlearn/p/10806461.html
總結
以上是生活随笔為你收集整理的环形队列的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。