【发布时间】:2021-04-03 14:06:00
【问题描述】:
我尝试使用以下代码将元素插入Descending Priority Queue。我很无助,因为这个问题有几个答案,人们将priority 作为用户的输入。在这里,我尝试使用以下条件进行排序:
#include<stdio.h>
#include<stdlib.h>
struct qElem
{
int ele;
int priority;
struct qElem *next;
};
struct queue
{
struct qElem *front, *rear;
int size;
};
void enQueue(struct queue *q, int ele)
{
struct qElem *temp;
temp = (struct qElem *) malloc (sizeof(struct qElem));
temp->ele = ele;
temp->next = NULL;
if (q->rear == NULL) {
q->rear = temp;
q->front = temp;
}
else if (q-> rear -> ele < temp->ele){
q-> rear = temp;
temp->next = q->rear;
}
++ q->size;
}
void display_pqueue(struct queue *q) {
if(q->front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct qElem *temp = q->front;
while(temp->next != NULL){
printf("%d--->",temp->ele);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->ele);
}
}
插入未按顺序进行。请在EnQueue 和Display 操作中帮助我。
【问题讨论】:
-
在队列中只能将节点添加到尾部。如果您需要在特定位置添加节点,那么您的数据结构就是链表。如果你被告知要创建一个队列,那么也许你应该按元素值的降序打印元素。
-
您的 enQueue 函数缺少迭代代码,以便按降序插入队列元素。因为您的队列没有特定限制,并且您无法知道在运行时可以排队多少项。
标签: c linked-list priority-queue