Home > other >  How to dequeue the smallest element from queue in C
How to dequeue the smallest element from queue in C

Time:11-20

I created a queue and enqueue some values. Then, I want to dequeue the smallest value from the queue. I got the smallest value by linear search. But I don't know how to deal with the front and rear after I find the smallest value.

#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;
  }
}


CodePudding user response:

items[min]=items[rear];
rear--;
  • Related