循环队列实现

非常简单的循环队列实现,仅包含入队列和出队列操作,cpp代码不超过100行,在座的各位都是软件开发小能手,因此功能不再赘述。

完整工程代码:https://github.com/satadriver/dataStruct

废话不说,直接上源码。

头文件:

#pragma once

#include "Element.h"


class Queue {


public:
	Queue();
	Queue(int size);
	~Queue();

	int isFull();

	int isEmpty();

	int enQueue(ELEMENT* e);

	int deQueue(ELEMENT* e);

	int getPayload();

protected:
	ELEMENT* mBase;
	ELEMENT* mHdr;
	ELEMENT* mTail;
	int mSize;

};

cpp文件:



#include "queue.h"

#define DEFAULT_QUEUE_SIZE 0x4000


Queue::Queue() {
	if (mBase == 0)
	{
		mBase = new ELEMENT[DEFAULT_QUEUE_SIZE];
		mSize = DEFAULT_QUEUE_SIZE;
		mHdr = mBase;
		mTail = mBase;
	}
}
Queue::Queue(int size) {
	if (mBase == 0)
	{
		mBase = new ELEMENT[size];
		mSize = size;
		mHdr = mBase;
		mTail = mBase;
	}
}
Queue::~Queue() {
	if (mBase)
	{
		delete[] mBase;
		mBase = 0;
		mTail = 0;
		mHdr = 0;
		mSize = 0;
	}
}

int Queue::isFull() {
	ELEMENT* next = mTail;
	if (next == mBase + mSize)
	{
		next = mBase;
	}
	else {
		next++;
	}

	if (next == mHdr)
	{
		return 1;
	}

	return 0;
}

int Queue::isEmpty() {
	return mHdr == mTail;
}

int Queue::getPayload() {
	if (mTail > mHdr)
	{
		return mTail - mHdr;
	}
	else {
		return mSize - (mHdr - mTail);
	}
}

int Queue::enQueue(ELEMENT* e) {

	*mTail = *e;

	mTail++;
	if (mTail == mBase + mSize)
	{
		mTail = mBase;
	}

	return getPayload();
}

int Queue::deQueue(ELEMENT* e) {
	if (mHdr == mTail)
	{
		return 0;
	}

	*e = *mHdr;

	mHdr++;
	if (mHdr == mBase + mSize)
	{
		mHdr = mBase;
	}

	return getPayload();
}

你可能感兴趣的:(数据结构和算法,算法,数据结构)