本文主要是介绍09 C语言实现优先级队列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//优先级队列是在链式存储的队列中修改了入队操作的代码
#include "stdio.h"
#include "stdlib.h"typedef int ElemType;
typedef struct node {ElemType data;struct node *next;
} linknode_t;typedef struct {linknode_t *front;linknode_t *rear;
} linkqueue_t;linkqueue_t *linkqueue_create() {linkqueue_t *queue = (linkqueue_t *) malloc(sizeof(linkqueue_t));if (queue == NULL) {exit(-1);}queue->front = queue->rear = (linknode_t *) malloc(sizeof(linknode_t));if (queue->front == NULL) {exit(-1);}queue->front->next = NULL;return queue;
}int linkqueue_enter(linkqueue_t *queue, ElemType value) {linknode_t *node = (linknode_t *) malloc(sizeof(linknode_t));if (node == NULL) {exit(-1);}node->data = value;node->next = NULL;//这里找位置进行插入linknode_t *pre = queue->front;while (pre->next && pre->next->data >= value) {//结束后 这个队列是从高到低排列 大的值先出pre = pre->next;}if (pre == queue->rear) {queue->rear->next = node;queue->rear = node;} else { // 核心在这里node->next = pre->next;pre->next = node;}return 1;
}int linkqueue_empty(linkqueue_t *queue) {return queue->front == queue->rear ? 1 : 0;
}ElemType linkqueue_out(linkqueue_t *queue) {if (linkqueue_empty(queue)) {return -1;}linknode_t *temp = queue->front;queue->front = queue->front->next;ElemType value = queue->front->data;free(temp);temp = NULL;return value;
}int main() {linkqueue_t *queue = linkqueue_create();printf("入队%d\n", linkqueue_enter(queue, 11));printf("入队%d\n", linkqueue_enter(queue, 12));printf("入队%d\n", linkqueue_enter(queue, 13));printf("入队%d\n", linkqueue_enter(queue, 14));printf("入队%d\n", linkqueue_enter(queue, 15));printf("%d\n", linkqueue_out(queue));printf("%d\n", linkqueue_out(queue));printf("%d\n", linkqueue_out(queue));printf("%d\n", linkqueue_out(queue));printf("%d\n", linkqueue_out(queue));printf("%d\n", linkqueue_out(queue));printf("%d\n", linkqueue_out(queue));printf("%d\n", linkqueue_out(queue));return 0;
}
运行效果
这篇关于09 C语言实现优先级队列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!