【问题标题】:How to dequeue the smallest element from queue in C如何从C中的队列中取出最小元素
【发布时间】: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;
  }
}


【问题讨论】:

  • 您需要处理的不仅仅是frontrear。您需要在删除条目之后压缩所有条目。也就是说,将删除后的每个条目复制到原始索引之前的索引。然后将后部减一。前面不需要做任何事情,除非它被移除以留下一个空队列,在这种情况下它需要设置为 -1。这就是文字中的算法。现在在一张纸上尝试一下,然后尝试编写代码。
  • 如果你总是想要队列中最小的项目,你应该实现一个min-heap

标签: c queue priority-queue


【解决方案1】:
items[min]=items[rear];
rear--;

【讨论】:

  • 如果items 是无序的,这是理想的,但队列通常是有序的,这样在这种情况下可能会导致问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多