キューのリニアインプリメンテーション

2106 ワード

前の文章に続いて直接コードを貼ります

#include <iostream>
using namespace std;

#define ElemType int
const int INIT_SIZE = 100;
const int INCREMENT_SIZE = 10;
// : 
class Queue{
private:
	int front;
	int rear;
	int queue_total_size;
	ElemType *data;
public:
	bool InitQueue(); // 
	void DestoryQueue(); // 
	void ClearQueue(); // 
	bool QueueEmpty(); // 
	int QueueLength(); // 
	void GetHead(ElemType &e); // 
	bool EnQueue(ElemType e); // e 
	bool DeQueue(ElemType &e); // , , e 
};
// 
bool Queue::InitQueue()
{
	this->front = this->rear = 0;
	this->data = (ElemType *)malloc(sizeof(ElemType) * INIT_SIZE);
	if(!this->data)
		return false;
	this->queue_total_size = INIT_SIZE;
	return true;
}
// 
void Queue::DestoryQueue()
{
	delete this->data;
}
// 
void Queue::ClearQueue()
{
	this->rear = this->front;
}
// 
bool Queue::QueueEmpty()
{
	return this->rear == this->front;
}
// 
int Queue::QueueLength()
{
	return rear;
}
// 
void Queue::GetHead(ElemType &e)
{
	e = this->data[front];
}
// 
bool Queue::EnQueue(ElemType e)
{
	if(this->rear < this->queue_total_size)
	{
		this->data = (ElemType *)realloc(this->data, sizeof(ElemType) * (this->queue_total_size + INCREMENT_SIZE));
		if(!this->data)
			return false;
		this->queue_total_size += INCREMENT_SIZE;
	}
	this->data[rear++] = e;
	return true;
}
// 
bool Queue::DeQueue(ElemType &e)
{
	e = this->data[front];
	front++;
	return true;
}
int main()
{
	int e;
	Queue queue;
	queue.InitQueue();
	queue.EnQueue(3);
	queue.EnQueue(4);
	queue.EnQueue(5);
	queue.DeQueue(e);
	cout<<e;
	return 0;
}