SethVan

trivial_circular_queue_in_c

Jun 6th, 2021
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define MAX 10
  5.  
  6. void enqueue();
  7. void dequeue();
  8. void display();
  9. void peek();
  10.  
  11. int qArray[MAX];
  12. int rear = -1;
  13. int front = -1;
  14.  
  15. int main()
  16. {
  17.     int choice = 0;
  18.  
  19.     while (1)
  20.     {
  21.         printf("1. Insert\n2. Delete\n3. Display\n4. "
  22.                "Peek\n5. Quit\nEnter your choice : ");
  23.         scanf(" %d", &choice);
  24.  
  25.         switch (choice)
  26.         {
  27.         case 1:
  28.             enqueue();
  29.             break;
  30.         case 2:
  31.             dequeue();
  32.             break;
  33.         case 3:
  34.             display();
  35.             break;
  36.         case 4:
  37.             peek();
  38.             break;
  39.         case 5:
  40.             exit(1);
  41.         default:
  42.             printf("Wrong choice \n");
  43.         }
  44.     }
  45.     return 0;
  46. }
  47.  
  48. void enqueue()
  49. {
  50.     int add_item;
  51.     int newRear = ((rear + 1) % MAX);
  52.     if (newRear == front)
  53.         printf("Queue overflow \n");
  54.     else
  55.     {
  56.         printf("Insert the element in queue : ");
  57.         scanf(" %d", &add_item);
  58.         if (front == -1)
  59.         {
  60.             front = 0;
  61.             rear = 0;
  62.             qArray[rear] = add_item;
  63.         }
  64.         else
  65.         {
  66.             rear = newRear;
  67.             qArray[rear] = add_item;
  68.         }
  69.     }
  70. }
  71.  
  72. void dequeue()
  73. {
  74.     if (front == -1)
  75.     {
  76.         printf("Queue underflow \n");
  77.         return;
  78.     }
  79.     else
  80.     {
  81.         printf("Element deleted from queue is %d\n", qArray[front]);
  82.         if (front == rear)
  83.         {
  84.             front = -1;
  85.             rear = -1;
  86.         }
  87.         else
  88.             front = ((front + 1) % MAX);
  89.     }
  90. }
  91.  
  92. void display()
  93. {
  94.     int i = 0;
  95.     if (front == -1)
  96.         printf("Queue is empty \n");
  97.     else
  98.     {
  99.         i = front;
  100.         printf("Queue is : \n[%d, ", qArray[i]);
  101.         while (((i++) % MAX) != rear)
  102.             printf("%d%s", qArray[i % MAX], (i) % MAX == rear ? "" : ", ");
  103.         printf("]\n\n");
  104.     }
  105. }
  106.  
  107. void peek()
  108. {
  109.     if (front != -1)
  110.         printf("front item = %d\n", qArray[front]);
  111.     else
  112.         printf("Queue is empty\n");
  113. }
Advertisement
Add Comment
Please, Sign In to add comment