队列之链式存储

链式队列

原理:

链式队列的存储结构不过是一个遵循头进尾出原则的单链表而已,我们将队头指针指向链队列的头结点,而队尾指针指向终端节点。

这是其结构体定义:

#define MAX_SIZE 5
typedef int dataType;
typedef struct _QNode{
	dataType data;
	void (*handler)(void);
	_QNode* next;
}QNode;

typedef QNode* QueuePtr;
typedef struct Queue {
	size_t length;
	QueuePtr front;
	QueuePtr rear;
}LinkQueue;

在这里我们每个节点的元素有指针QNode,int类型数据data,以及返回类型为空,参数为空的函数指针handler,指向task1或task2用来模拟每个节点中存放的任务。
任务task1和task2定义如下

void task1() {
	cout << "搬砖头!" << endl;
}
void task2() {
	cout << "造房子!" << endl;
}

算法实现

初始化队列

//初始化LQ,使其长度为0,front和rear指向NULL
bool initLinkQueue(LinkQueue*& LQ) {
	if (!LQ) return false;
	LQ->length = 0;
	LQ->front = NULL;
	LQ->rear = NULL;
	return true;
}

判断队列存储情况(是否为空,是否为满)

bool isLQFull(LinkQueue*& LQ) {
	if (!LQ) return false;
	if (LQ->length == MAX_SIZE) return true;
	return false;
}
bool isLQEmpty(LinkQueue*& LQ) {
	if (!LQ) return false;
	if (LQ->front == NULL) return true;
	return false;
}

队尾插入元素

//参数worktype决定了任务的类型,传入为0,则任务1,反之任务1
bool LinkQueueInsert(LinkQueue*& LQ, dataType data,int workType) {
	if (!LQ) return false;
	if (isLQFull(LQ)) {
		cout << "队列已满,无法继续插入元素!" << endl;
		return false;
	}
	QueuePtr p = NULL;
	p = new	QNode;
        p->data = data;
	switch (workType) {
	case 1:p->handler = &task2;
		break;
	case 0:p->handler = &task1;
		break;
	}
	p->next = NULL;
	if (isLQEmpty(LQ)) {
		LQ->front = p;
		LQ->rear = p;
	}
	else if (!isLQEmpty(LQ)) {
		LQ->rear->next = p;
		LQ->rear = p;
	}
	LQ->length++;
	return true;
}

队首出去一个元素

bool LinkQueueDelete(LinkQueue*& LQ) {
	if (!LQ || isLQEmpty(LQ)) return false;
	QueuePtr tmp = LQ->front;
	LQ->front = LQ->front->next;
	delete tmp;
	if (!LQ->front) LQ->rear = NULL;
	LQ->length--;
	return true;
}

清除队列中所有元素

//清除队列中的所有元素,释放LQ指向的内存并将,LQ指向NULL
bool LinkQuequeDestroy(LinkQueue*& LQ) {
	if (!LQ) return false;
	while (LQ->front) {
		LinkQueueDelete(LQ);
	}
	delete LQ;
	LQ = NULL;
	return true;
}

遍历队列中所有元素

bool printLQ(LinkQueue*& LQ){
	if (!LQ) return false;
	if (isLQEmpty(LQ)) {
		cout << "队列中尚未存储元素!" << endl;
		return false;
	}
	QueuePtr p = LQ->front;
	while (p) {
		cout << "开始任务" << endl;
		cout << p->data << endl;
		p->handler();
		p = p->next;
	}
	return true;
}

测试函数

void testLQ() {
	LinkQueue* LQ = new LinkQueue;
	initLinkQueue(LQ);
	printLQ(LQ);
	for (int i = 0;i < 10;i++) {
		LinkQueueInsert(LQ, i,i%2);
	}
	printLQ(LQ);
	for (int i = 0;i <5;i++) {
		LinkQueueDelete(LQ);
	}
	cout << "---------出队五个任务之后------------"<<endl;
	printLQ(LQ);
	cout << "---------销毁队列后------------" << endl;
	LinkQuequeDestroy(LQ);
	printLQ(LQ);

}

就这样

posted @ 2020-05-11 15:18  YBossy  阅读(348)  评论(0)    收藏  举报