使用链表实现优先队列 (C语言)


给定数据和优先级(整数),任务是根据给定的优先级创建一个链表并显示结果。

队列是一种先进先出 (FIFO) 数据结构,其中最先插入的元素也是最先被删除的元素。优先队列是一种队列,其中元素的插入和删除取决于优先级。它可以使用队列、栈或链表数据结构来实现。优先队列的实现遵循以下规则:

  • 具有最高优先级的数 据或元素将优先于具有最低优先级的数 据或元素执行。
  • 如果两个元素具有相同的优先级,则它们将按照添加到列表中的顺序执行。

用于实现优先队列的链表节点将包含三个部分:

  • 数据 - 它将存储整数值。
  • 地址 - 它将存储下一个节点的地址。
  • 优先级 - 它将存储优先级,这是一个整数值。它的范围可以是 0-10,其中 0 代表最高优先级,10 代表最低优先级。

示例

输入

输出

算法

Start
Step 1-> Declare a struct node
   Declare data, priority
   Declare a struct node* next
Step 2-> In function Node* newNode(int d, int p)
   Set Node* temp = (Node*)malloc(sizeof(Node))
   Set temp->data = d
   Set temp->priority = p
   Set temp->next = NULL
   Return temp
Step 3-> In function int peek(Node** head)
   return (*head)->data
Step 4-> In function void pop(Node** head)
   Set Node* temp = *head
   Set (*head) = (*head)->next
   free(temp)
Step 5-> In function push(Node** head, int d, int p)
   Set Node* start = (*head)
   Set Node* temp = newNode(d, p)
   If (*head)->priority > p then,
      Set temp->next = *head
      Set (*head) = temp
   Else
   Loop While start->next != NULL && start->next->priority < p
      Set start = start->next
      Set temp->next = start->next
      Set start->next = temp
Step 6-> In function int isEmpty(Node** head)
   Return (*head) == NULL
Step 7-> In function int main()
   Set Node* pq = newNode(7, 1)
   Call function push(&pq, 1, 2)
   Call function push(&pq, 3, 3)
   Call function push(&pq, 2, 0)
   Loop While (!isEmpty(&pq))
   Print the results obtained from peek(&pq)
   Call function pop(&pq)
Stop

示例

在线演示

#include <stdio.h>
#include <stdlib.h>
// priority Node
typedef struct node {
   int data;
   int priority;
   struct node* next;
} Node;
Node* newNode(int d, int p) {
   Node* temp = (Node*)malloc(sizeof(Node));
   temp->data = d;
   temp->priority = p;
   temp->next = NULL;
   return temp;
}
int peek(Node** head) {
   return (*head)->data;
}
void pop(Node** head) {
   Node* temp = *head;
   (*head) = (*head)->next;
   free(temp);
}
void push(Node** head, int d, int p) {
   Node* start = (*head);
   Node* temp = newNode(d, p);
   if ((*head)->priority > p) {
      temp->next = *head;
      (*head) = temp;
   } else {
      while (start->next != NULL &&
      start->next->priority < p) {
         start = start->next;
      }
      // Either at the ends of the list
      // or at required position
      temp->next = start->next;
      start->next = temp;
   }
}
// Function to check the queue is empty
int isEmpty(Node** head) {
   return (*head) == NULL;
}
// main function
int main() {
   Node* pq = newNode(7, 1);
   push(&pq, 1, 2);
   push(&pq, 3, 3);
   push(&pq, 2, 0);
   while (!isEmpty(&pq)) {
      printf("%d ", peek(&pq));
      pop(&pq);
   }
   return 0;
}

输出

2 7 1 3

更新于:2019年12月23日

4K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.