priority queue in c
A priority Queue is an extension of the queue with some specific properties.
- Every item has a priority associated with it.
- An element with high priority is dequeued before an element with low priority.
- If two elements have the same priority, they are served according to their order in the queue.
A typical priority queue supports the following operations.
- qinsert(): Inserts an item with a given priority.
- qdisplay(): Display queue elements in priority order.
- qdelete(): Removes the highest priority item.
priority queue in c using linked list
Declaring priority queue
struct pqueue { int key; int data; struct pqueue*next; }; typedef struct pqueue QUEUE; QUEUE*front=NULL;
QInsert operation
void qinsert() { QUEUE*temp,*q; temp=(QUEUE*)malloc(sizeof(QUEUE)); printf("\nEnter key: "); scanf("%d",&temp->key); printf("\nEnter data: "); scanf("%d",&temp->data); if(front==NULL||temp->key < front->key) { temp->next=front; front=temp; return; } else { q=front; while( q->next!=NULL&&q->next->key<=temp->key) q=q->next; temp->next=q->next; q->next=temp; return; } }
QDelete operation
void qdelete() { QUEUE*temp; if(front==NULL) { printf("\nQUEUE IS UNDERFLOW(EMPTY):"); return; } else { temp=front; front=front->next; temp->next=NULL; printf("\ndeleted data:%d",temp->data); free(temp); temp=NULL; return; } }
QDisplay operation
void qdisplay() { QUEUE*temp; if(front==NULL) { printf("\nQUEUE IS EMPTY: "); return; } else { printf("\nQUEUE DATA: "); temp=front; do { printf("%d ",temp->data); temp=temp->next; }while(temp!=NULL); } }
main() implementation
int main() { int option; while(1) { clrscr(); printf("\n1.FOR INSERT :"); printf("\n2.FOR DELETE :"); printf("\n3.FOR DISPLAY: "); printf("\n4.FOR EXIT...:"); scanf("%d",&option); switch(option) { case 1: qinsert(); break; case 2: qdelete(); getch(); break; case 3: qdisplay(); getch(); break; case 4: return 0; default: printf("\ninvalid option: "); } } }