Priority Queue

#include <cstdio> #include <cstdlib> struct Node { int data; int priority; Node *next; } *Head; int display() { if (Head == NULL) printf("Queue is Empty"); else { printf("Priority\tData\n"); for (Node *Current = Head; Current != NULL; Current = Current -> next) printf("%d\t%d\n", Current -> priority, Current -> data); printf("\n\n"); } } void insertPriority(int P, int D) { Node *NewNode = new Node; NewNode -> data = D; NewNode -> priority = P; NewNode -> next = NULL; if (Head == NULL) Head = NewNode; else { Node *Left, *Right; for (Right = Head; Right; Left = Right, Right = Right -> next) { if (Right -> priority > NewNode -> priority) break; else if (Right -> priority == NewNode -> priority && Right -> data > NewNode -> data) break; } if (Right == Head) { NewNode -> next = Head; Head = NewNode; } else { Left -> next = NewNode; NewNode -> next = Right; } } } int Delete() { if (Head == NULL) return 0; else { int num = Head -> data; Node *Current = Head; Head = Head -> next; free(Current); return num; } } int main() { int choice, num, pr; Head = NULL; while (1) { printf("List Operations: \n"); printf("================\n"); printf("1. Add\n"); printf("2. Display\n"); printf("3. Delete\n"); printf("4. Exit\n"); printf("Choice: "); scanf("%d", &choice); switch (choice) { case 1: { printf("Enter the Priority: "); scanf("%d", &pr); printf("Enter the Number: "); scanf("%d", &num); insertPriority(pr, num); break; } case 2: { display(); break; } case 3: { if (Head == NULL) printf("List is Empty. Nothing to Delete.\n"); else { num = Delete(); if (num != 0) printf("Successfully Deleted %d\n", num); else printf("%d Not Deleted.\nValue Might Not Found\n", num); } break; } case 4: { exit(0); } default: { printf("Invalid Input. Try Again\n"); } } printf("\n\n"); } return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.