您的位置:首页 > 理论基础 > 数据结构算法

C++类模板 实现循环队列的顺序存储结构算法 《数据结构》(北京科海) 部分摘抄 自己编写实现

2012-11-19 15:16 891 查看
      循环队列的顺序存储结构

      这里需说明一点:满队列时实际仍有一个元素的空间未使用,(rear+1)%maxSize == front 为满队列判断条件。若不留这个元素空间,则队尾指针rear一定指向该元素空间,使得满队列时的判断条件也是front == rear,则与空队列的判断条件相同而导致无法区分。

         代码实现如下:

/*
Filename: SeqQueue.h
Description: The Sequential storage structure of quequ.
Date: November 19, 2012
*/

#ifndef SEQQUEUE_H
#define SEQQUEUE_H

//#include <queue>
#include <iostream>
using namespace std;

const int MAXSIZE = 5;

//循环队列类定义
template<class T>
class SeqQueue
{
public:
SeqQueue()
{
new_q = new T[MAXSIZE];
front = rear = 0;
}

~SeqQueue()
{
delete new_q;
}

public:
bool IsEmpty();
bool IsFull();
bool Front(T &x); //获得队列首值
int Length();
bool EnQueue(T x);  //进队列
bool DeQeue(); //出队列
void Print();
int Getfront();
int Getrear();

private:
int front, rear;
T *new_q;

};

//循环队列类实现
template<class T>
bool SeqQueue<T>::IsEmpty()
{
if (front == rear)
{
return true;
}

return false;
}

template<class T>
bool SeqQueue<T>::IsFull()
{
if (front == (rear+1) % MAXSIZE)
{
return true;
}

return false;
}

template<class T>
int SeqQueue<T>::Length()
{
return (rear-front+MAXSIZE) % MAXSIZE;
}

template<class T>
bool SeqQueue<T>::Front(T  &x)
{
if (!IsEmpty())
{
x = new_q[front];
return true;
}
else
{
cout << "Empty" << endl;
return false;
}

}

template<class T>
bool SeqQueue<T>::EnQueue(T x)
{
if (IsFull())
{
cout << "Full" << endl;
return false;
}
else
{
new_q[rear] = x;
rear = (rear+1) % MAXSIZE;
return true;
}
}

template<class T>
bool SeqQueue<T>::DeQeue()
{
if (IsEmpty())
{
cout << "Underflow" << endl;
return false;
}

front = (front+1) % MAXSIZE;
return true;
}

template<class T>
void SeqQueue<T>::Print()
{
if (!IsEmpty())
{
int tempNum = front;

while (tempNum != rear)
{
cout << new_q[tempNum] << " " ;
tempNum = (tempNum+1) % MAXSIZE;
}

cout << endl;
}
}

template<class T>
int SeqQueue<T>::Getfront()
{
return front;
}

template<class T>
int SeqQueue<T>::Getrear()
{
return rear;
}

#endif

#include "SeqQueue.h"

int main()
{
SeqQueue<int> Se;
Se.EnQueue(2);
Se.EnQueue(4);
Se.EnQueue(6);
Se.Print();
cout << "------------------------" << endl;

Se.EnQueue(5);
Se.EnQueue(3);
Se.Print();
cout << "------------------------" << endl;

cout << "队列长度:" << Se.Length() << endl;
int front_date;
Se.Front(front_date);
cout << "队列首元素:" << front_date << endl;
cout << "front值:" << Se.Getfront() << endl;
cout << "rear值:" << Se.Getrear() << endl;
Se.DeQeue();
Se.DeQeue();
Se.Print();
cout << "------------------------" << endl;

Se.EnQueue(100);
Se.EnQueue(101);
Se.Print();
Se.Front(front_date);
cout << "队列首元素:" << front_date << endl;
cout << "front值:" << Se.Getfront() << endl;
cout << "rear值:" << Se.Getrear() << endl;
cout << "------------------------" << endl;

system("pause");
return 0;
}


     有什么错误之处,请大家指出来,互相学习,希望我写的代码,能帮到你.......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: