Advertisement
skb50bd

[207Lec4]CircularQueueWithArray

May 26th, 2016
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <iostream>
  2. #define MAX 5
  3. using namespace std;
  4.  
  5. int Q[MAX];
  6. int head = -1;
  7. int tail = -1;
  8. int count = 0;
  9.  
  10. bool isEmpty() {
  11.     if (count == 0) return true;
  12.     else return false;
  13. }
  14.  
  15. bool isFull() {
  16.     if (count == MAX) return true;
  17.     else return false;
  18. }
  19.  
  20. void display() {
  21.     if (count) {
  22.         for (int i = 0, j = head; i < count; i++, ++j %= MAX)
  23.             cout << Q[j] << " ";
  24.         cout << endl;
  25.     }
  26.     else cout << "Queue is Empty" << endl;
  27. }
  28.  
  29. void enqueue(int x) {
  30.     if (isFull()) {
  31.         cout << "Cannot Enqueue " << x << endl;
  32.         cout << "Queue is Full/OverFlow" << endl;
  33.     }
  34.     else {
  35.         Q[++tail % MAX] = x;
  36.         if (isEmpty()) head++;
  37.         count++;
  38.     }
  39.     display();
  40. }
  41.  
  42. void dequeue() {
  43.     if (count) {
  44.         ++head %= MAX;
  45.         count--;
  46.         if (isEmpty()) {
  47.             head = -1;
  48.             tail = -1;
  49.         }
  50.         display();
  51.     }
  52.     else {
  53.         cout << "Cannot Dequeue" << endl;
  54.         cout << "Queue is Empty/Underflow" << endl;
  55.     }
  56. }
  57.  
  58.  
  59.  
  60.  
  61. int main() {
  62.     int choice, value;
  63.  
  64.     while (true) {
  65.         cout << "1. Enqueue" << endl;
  66.         cout << "2. Dequeue" << endl;
  67.         cout << "3. Display" << endl;
  68.         cout << "4. Quit" << endl;
  69.         cout << "Choice: ";
  70.         cin >> choice;
  71.  
  72.         if (choice == 1) {
  73.             cout << "Enter value to Enqueue: ";
  74.             cin >> value;
  75.             enqueue(value);
  76.         }
  77.         else if (choice == 2) dequeue();
  78.         else if (choice == 3) display();
  79.         else if (choice == 4) break;
  80.         else cout << "Invalid Choice" << endl;
  81.  
  82.         cout << endl;
  83.     }
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement