+ 2

Can anyone help me in this this is what I have done upto but something is still missing

#include <iostream> using namespace std; class Queue { int size; int* queue; int rear; int count; public: Queue(int a) { size = a; queue = new int[size]; rear = -1; count = 0; } void remove() { if (size == 0) { cout << "Queue is empty"<<endl; return; } else { for (int i = 0; i < size ; i++) { queue[i] = queue[i + 1]; } size--; } } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout <<endl; } //your code goes here void add(int x) { if(size <= 0) {cout<<"Empty";} else { rear = (rear + 1) % size; queue[rear] = x; count++; } } }; int main() { Queue q(7); q.add(42); q.add(2); q.add(8); q.add(1); q.print(); q.remove(); q.add(128); q.print(); q.remove(); q.remove(); q.print(); return 0; }

18th Jan 2021, 11:00 AM
Om Nandgirwar
Om Nandgirwar - avatar
1 Answer
+ 1
1. The size of the queue must be 0 at first. It has the capacity of holding n number but it's empty at first. 2. Declaring "rear" and "count" is unnecessary. 3. The "add" function doesn't need to check any condition. It's simply add an element at the end of the queue. Using "size" variable is sufficient for adding new element. My code is as follows: #include <iostream> using namespace std; class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } void remove() { if (size == 0) { cout << "Queue is empty"<<endl; return; } else { for (int i = 0; i < size - 1; i++) { queue[i] = queue[i + 1]; } size--; } } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout <<endl; } void add(int element) { queue[size] = element; ++size; } }; int main() { Queue q; q.add(42); q.add(2); q.add(8); q.add(1); q.prin
18th Jan 2021, 5:46 PM
Mohammad Reza Sharifi Khorasani
Mohammad Reza Sharifi Khorasani - avatar