【发布时间】:2021-11-19 22:26:44
【问题描述】:
我创建了一个队列并将一些值排入队列。然后,我想从队列中取出最小值。我通过线性搜索得到了最小值。但是我不知道找到最小值后如何处理前后。
#include <stdio.h>
#define SIZE 5
void enQueue(int);
void deQueue();
int items[SIZE], front = -1, rear = -1;
int main() {
enQueue(3);
enQueue(5);
enQueue(4);
enQueue(1);
enQueue(2);
printf("Deleted value is %d\n",deQueue());
return 0;
}
void enQueue(int value) {
if (rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (front == -1)
front = 0;
rear++;
items[rear] = value;
printf("\nInserted -> %d", value);
}
}
int deQueue() {
if (front == -1)
exit(1);
else {
int min=0;
for(int i=front;i<rear;i++){
if(items[min]>items[i])
min=i;
}
int value=items[min];
//What should I do then for front and rear in order to remove the deleted value
return value;
}
}
【问题讨论】:
-
您需要处理的不仅仅是
front和rear。您需要在删除条目之后压缩所有条目。也就是说,将删除后的每个条目复制到原始索引之前的索引。然后将后部减一。前面不需要做任何事情,除非它被移除以留下一个空队列,在这种情况下它需要设置为 -1。这就是文字中的算法。现在在一张纸上尝试一下,然后尝试编写代码。 -
如果你总是想要队列中最小的项目,你应该实现一个min-heap
标签: c queue priority-queue