assignment_09.cpp (2018B)
1 /* Perform Queues operations using Array. */ 2 3 #include <iostream> 4 using namespace std; 5 6 class Queue { 7 private: 8 int *arr; 9 int front, rear, capacity; 10 11 public: 12 Queue(int size) { 13 capacity = size; 14 arr = new int[capacity]; 15 front = -1; 16 rear = -1; 17 } 18 19 bool isFull() { return (rear == capacity - 1); } 20 bool isEmpty() { return (front == -1 || front > rear); } 21 22 void enqueue() { 23 if (isFull()) { cout << "Queue Overflow!\n"; return; } 24 int val; 25 cout << "Enter the value: "; 26 cin >> val; 27 if (front == -1) front = 0; 28 arr[++rear] = val; 29 } 30 31 void dequeue() { 32 if (isEmpty()) { cout << "Queue Underflow!\n"; return; } 33 int val = arr[front++]; 34 if (front > rear) { front = -1; rear = -1; } 35 cout << "Dequeued value: " << val << endl; 36 } 37 38 void peek() { 39 if (isEmpty()) { cout << "Queue is empty!\n"; return; } 40 cout << "Front element: " << arr[front] << endl; 41 } 42 43 void display() { 44 if (isEmpty()) { cout << "Queue is empty!\n"; return; } 45 for (int i = front; i <= rear; i++) cout << arr[i] << " "; 46 cout << endl; 47 } 48 49 ~Queue() { delete[] arr; } 50 }; 51 52 int main() { 53 int size, choice; 54 cout << "Enter queue capacity: "; 55 cin >> size; 56 if (size <= 0) { cout << "Invalid size!\n"; return 0; } 57 58 Queue q(size); 59 while (true) { 60 cout << "1.enqueue 2.dequeue 3.peek 4.isFull 5.isEmpty 0.Display -1.Exit\n"; 61 cout << "Enter your choice: "; 62 cin >> choice; 63 64 switch (choice) { 65 case 1: q.enqueue(); break; 66 case 2: q.dequeue(); break; 67 case 3: q.peek(); break; 68 case 4: cout << (q.isFull() ? "Full\n" : "Not full\n"); break; 69 case 5: cout << (q.isEmpty() ? "Empty\n" : "Not empty\n"); break; 70 case 0: q.display(); break; 71 case -1: cout << "Exiting...\n"; return 0; 72 default: cout << "Wrong choice.\n"; 73 } 74 } 75 }