Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

insert nod, new, into sorted priority queue 4. Priority Queue (3 points) Suppose

ID: 3867941 • Letter: I

Question

insert nod, new, into sorted priority queue


4. Priority Queue (3 points) Suppose linked list as follows: we define a priority queue using a circular doubly / Linked list node */ /* info stored in this node / /* Pointer to the next node in linked list /*Cor the front node of LL if this is the rear node) / struct node f int info; struct node *next; Pointer to the next node in linked list / /*Cor the rear node of LL if this is the front node) / node *prev j: /*Priority queue */ /*Number of elements in queue */ struct pq f int size; struct node *front /* Pointer to the first node / struct node rear* Pointer to the last node / J; te an iterative (i.e.. given node, new, into a sorted priority queue. void insert (struct pg *queue, struct node *new) ( ne

Explanation / Answer

void insert(struct pq *queue, struct node *new){

    struct node *ptr;
    ptr = queue->front;
    if (ptr == NULL){
        new->prev = new;
        new->next = new;
        queue->front = new;
        queue->rear = new;
        return;
    }
    if (ptr->info > new->info){
          new->next = ptr;
          new->prev = ptr->prev;
          ptr->prev = new;
          queue->front = new;
    }
    else {
        while (ptr != NULL && ptr->info < new->info){
             ptr = ptr->next;
        }
        if (ptr == NULL){
           new->next = queue->rear->next;
           new->prev = queue->rear;
           queue->rear->next = new;
           queue->rear = new;
        }
        else {
            new->next = ptr;
            ptr->prev->next = new;
            new->prev = ptr->prev;
            ptr->prev = new;
        }
    }
}