priority_queue.h
#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H
// 队列可以满足对任意数据的存取 union 对于数据类型的判断
typedef unsigned int uint;
typedef struct queue_node
{
void *data;
struct queue_node *prev;
struct queue_node *next;
}QNode;
typedef struct queue
{
// 队长度
uint length;
// 队的最大长度
uint max_length;
QNode *head;
QNode *tail;
}Queue;
// 创建空队列
Queue *create_queue();
// 通用指针域入队
void queue_enter(Queue *queue, void *data);
// 出
void *queue_exit(Queue *queue);
// // 打印队列信息
// void display_queue(Queue *queue);
// 摧毁
void destry_queue(Queue **queue);
// 队列优先级化
Queue *priority(Queue *queue);
#endif
priority_queue.c
#include <stdio.h>
#include <stdlib.h>
#include "priority_queue.h"
// 创建
Queue *create_queue()
{
Queue *q = (Queue *)malloc(sizeof(Queue));
q->length = 0;
q->max_length = 1024;
q->head = NULL;
q->tail = NULL;
return q;
}
// 数据指针域入队,数组,结构体等通用
void queue_enter(Queue *queue, void *data)
{
QNode *n = (QNode *)malloc(sizeof(QNode));
n->data = data;
n->prev = NULL;
n->next = NULL;
// 普通队列的操作
if (queue->length == 0)
{
queue->head = n;
queue->tail = n;
queue->length++;
}
else
{
queue->tail->next = n;
n->prev = queue->tail;
queue->tail = n;
queue->length++;
}
}
// 出
void *queue_exit(Queue *queue)
{
QNode *temp = queue->head;
// 出队相关的操作
if (queue->length == 0)
{
return NULL;
}
else if (queue->length == 1)
{
queue->head = NULL;
queue->tail = NULL;
}
else
{
queue->head = temp->next;
queue->head->prev = NULL;
temp->next = NULL;
}
queue->length--;
return temp->data;
}
void display_queue(Queue *queue)
{
struct queue_node *index = queue->head;
if (index == NULL)
{
printf("NULL");
}
else
{
while (index != NULL)
{
printf("%d ", *(int *)(index->data));
index = index->next;
}
printf("\n");
}
}
// 摧毁
void destry_queue(Queue **queue)
{
QNode *temp;
while ((*queue)->length > 0)
{
temp = (*queue)->head;
if ((*queue)->length == 1)
{
(*queue)->head = NULL;
(*queue)->tail = NULL;
}
else
{
(*queue)->head = temp->next;
(*queue)->head->prev = NULL;
temp->next = NULL;
}
free(temp);
(*queue)->length--;
}
free(*queue);
*queue = NULL;
}
void bubble_node(Queue *queue, QNode *prev, QNode *cur)
{
if (prev->prev != NULL)
{
prev->prev->next = cur;
}
cur->prev = prev->prev;
prev->prev = cur;
prev->next = cur->next;
if (cur->next != NULL)
{
cur->next->prev = prev;
}
cur->next = prev;
}
Queue *priority(Queue *queue)
{
if (queue->head == queue->tail)
{
return queue;
}
else
{
QNode *index = queue->tail;
int flag = 0;
while (index->prev != NULL)
{
//这里的强制类型转换要根据队列元素的具体指针类型修改,下面是int型数组入队进行优先级排序的的情况,比较的是数组值的大小
if (*(int *)index->data < *(int *)index->prev->data)
{
bubble_node(queue, index->prev, index);
// 调整队尾
if (flag == 0)
{
queue->tail = index->prev;
flag = 1;
}
}
else
{
return queue;
}
}
// 调整队头
queue->head = index;
}
}