数据结构——顺序队列的C++实现

peSqQueue.cpp

#include "peSqQueue.h"

typedef int Statue;

#define SQQUEUE_STATUE_SUCCESS	0
#define SQQUEUE_STATUE_ERROR	1
  
template<class T> 
class peSqQueue
{
public:
	peSqQueue(int size);
	~peSqQueue(void);

	T* data;
	int QueueSize;//队列最大长度
	int front;//头指针
	int rear;//尾指针

	int GetQueueLen(void);
	Statue Insert(T e);
	Statue Delete(void);
	Statue Delete(T* e);
};

template<class T>
peSqQueue<T>::peSqQueue(int size)
{
	data = new T[size];
	front = 0;
	rear = 0;
	QueueSize = size;
}

template<class T>
peSqQueue<T>::~peSqQueue(void)
{
	delete[] data;
}

template<class T>
int peSqQueue<T>::GetQueueLen(void)
{
	return ((rear - front + QueueSize) % QueueSize);
}

template<class T>
Statue peSqQueue<T>::Insert(T e)
{
	if(((rear + 1) % QueueSize) == front)
	{
		return SQQUEUE_STATUE_ERROR;
	}//((rear + 1) % QueueSize) == front

	data[rear] = e;
	rear = (rear + 1) % QueueSize;
	return SQQUEUE_STATUE_SUCCESS;
}

template<class T>
Statue peSqQueue<T>::Delete(void)
{
	if(front == rear)
	{
		return SQQUEUE_STATUE_ERROR;
	}//front == rear

	front = (front + 1) % QueueSize;

	return SQQUEUE_STATUE_SUCCESS;
}

template<class T>
Statue peSqQueue<T>::Delete(T* e)
{
	if(front == rear)
	{
		return SQQUEUE_STATUE_ERROR;
	}//front == rear

	*e = data[front];
	front = (front + 1) % QueueSize;

	return SQQUEUE_STATUE_SUCCESS;
}
Main.cpp

#include <iostream>  
#include "peSqQueue.cpp"
using namespace std;  
  
int main()  
{  
	peSqQueue<int> Squeue(11);

	Squeue.Insert(1);
	Squeue.Insert(3);
	Squeue.Insert(5);
	Squeue.Insert(7);
	Squeue.Insert(9);
	Squeue.Insert(11);
	Squeue.Insert(13);
	Squeue.Insert(15);
	Squeue.Insert(17);
	Squeue.Insert(19);

	Squeue.Delete();
	Squeue.Delete();
	Squeue.Delete();
  
    int len = Squeue.GetQueueLen();
	cout << "the length of SqQueue:" << len << endl;

	cout << "Printf the SqQueue:" << endl;
	if(Squeue.rear < Squeue.front)
	{
		for(int i = Squeue.front; i < len; ++i)
		{
			cout << Squeue.data[i] << endl;
		}//i
		for(int j = 0; j < Squeue.rear; ++j)
		{
			cout << Squeue.data[j] << endl;
		}//j
	}//Squeue.rear < Squeue.front
	else
	{
		for(int i = Squeue.front; i < Squeue.rear; ++i)
		{
			cout << Squeue.data[i] << endl;
		}//i	
	}
	
	system("pause");  
    return 0;  
}

程序运行结果:

数据结构——顺序队列的C++实现_第1张图片

你可能感兴趣的:(数据结构,C++,学习笔记,队列)