数据结构和算法—优先队列

优先队列

优先队列和普通的队列相同,只有出队方式不同…优先队列是按照优先级的高低来进行出列的,其它和不同队列类同…

优先队列出队

  1. 定义一个二级指针保存最高优先级的地址
  2. 定义一个指针保存最高优先级的前一个节点
  3. 定义俩个一级指针保存第一个和第二节点, 它俩个指针保存的节点中的优先级进行比较,比较后均向后移动…

代码实现

#include <iostream>
#include <Windows.h>
#include <stdio.h>

#define MAX_SIZE	100

// 优先队列的定义
typedef int ELEM;
typedef struct _Node {
	int priority;	// 优先级, 出队时,根据优先级的高低出队
	ELEM date;
	struct _Node* next;	//用来连接下一个节点
}Node;

typedef Node* QueuePrt;


typedef struct _PrioQueue {
	int length;	//长度
	QueuePrt front;	//头
	QueuePrt rear;	//尾
}PrioQueue;

// 初始化优先队列
bool initPrioQueue(PrioQueue* &pq) {
	pq = new PrioQueue;
	if(!pq) return false;

	pq->length = 0;
	pq->front = pq->rear = NULL;
	return true;
}

// 优先队列为空
bool PrioEmpty(PrioQueue* pq) {
	if(!pq) return false;
	
	if(pq->front == NULL) return true;
	
	return false;
}

// 优先队列为满
bool PrioFull(PrioQueue* pq) {
	if(!pq) return false;
	
	if(pq->length >= MAX_SIZE) return true;
	
	return false;
}

// 优先队列入队
bool EnPrioQueue(PrioQueue* &pq, Node& node) {
	if(!pq || PrioFull(pq)) return false;
	
	Node* p = new Node;
	if(!p) return false;

	*p = node;
	p->next = NULL;
	// 1. 空队    2.已有入队
	if(pq->front == NULL) {
		pq->front = pq->rear = p;
	} else {
		pq->rear->next = p;
		pq->rear = p;
	}

	pq->length++;
	return true;
}

// 优先队列出队
bool DePrioQueue(PrioQueue* &pq, ELEM& node) {
	if(!pq || PrioEmpty(pq)) return false;

	// 找出最高优先级
	Node** prev = &pq->front;	//保存优先级最高的前一个节点的地址
	Node* prev_node = NULL;		//保存优先级最高的前一个节点
	Node* last = pq->front;		//指向第一个
	Node* temp = last->next;	//指向第二个

	while(temp) {
		if(last->priority < temp->priority) {
			printf("找到一个更大优先级:%d\n", temp->priority);
			prev = &last->next;
			prev_node = last;
		}
		// 均指向下一个
		last = last->next;
		temp = temp->next;
	}

	temp = *prev;
	*prev = (*prev)->next;
	pq->length--;

	//1. 删除元素后, 队列为空
	if(pq->length <= 0) {
		pq->rear = NULL;
	}
	
	//2. 删除的是尾节点, 需要调整rear指针
	if(prev_node && prev_node->next == NULL) {
		pq->rear = prev_node;
	}
	
	//3.删除的是中间节点, 不需要调整

	return true;	
}

// 优先队列的遍历
void PrintPrioQueue(PrioQueue* pq) {
	if(!pq || !pq->front) return;	// 参数不合法或 队列为空
	
	Node* p = pq->front;
	while(p) {
		printf("priority:[%d]  date:[%d]\t", p->priority, p->date);
		p = p->next;
	}
	printf("\n");
}

// 获取对头元素, 不实现了, 没有意义

// 获取长度
int length(PrioQueue* pq) {
	if(!pq) return -1;

	return pq->length;
}

// 清空优先队列
bool ClearPrioQueue(PrioQueue* &pq) {
	if(!pq) return false;
	Node* p = pq->front;
	while(p) {
		pq->front = p->next;
		delete p;
		p = pq->front;
	}

	pq->front = pq->rear = NULL;
	return true;
}

int main(void) {


}


发布了18 篇原创文章 · 获赞 2 · 访问量 221

猜你喜欢

转载自blog.csdn.net/weixin_44238530/article/details/102656524