0

Can you please explain this?

#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; } //your code goes here void add(int x) { queue[size++] = x; } }; int main() { Queue q; 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; } Specially, the remove and add method

16th Apr 2021, 12:59 AM
Mohammad Mehedi Hasan
Mohammad Mehedi Hasan - avatar
4 Answers
+ 1
So I guess you know that queue is a first in first out structure right? So just an example of the queue given in the codes, it'd be something like this [42] add 42 [42, 2] add 2 [42, 2 ,8] add 8 [42, 2, 8, 1] add 1 [2, 8, 1] ---first remove And so on So what happen is that you want to always add to the end of the queue, and the end of the queue is precisely at index *size*, and after you add, you'd want to increment the size (because 1 more item), therefore you do queue[size] = x; size++; or combine together as shown in the codes. For remove part, basically remove the first element by bringing every element at the back to the front, using the first remove above, it'll be like this [42, 2, 8, 1] [2, 2, 8, 1] [2, 8, 8, 1] [2, 8, 1, 1] [2, 8, 1] - don't have to care for the last 1, it'll be overwritten if there's another add So, basically remove is done by pushing every element one step forward, overwriting the element in front of it(therefore the first element is 'removed')
16th Apr 2021, 2:44 AM
Hoh Shen Yien
Hoh Shen Yien - avatar
0
Hoh Shen Yien oOo, Ok, Thanks.
16th Apr 2021, 3:39 AM
Mohammad Mehedi Hasan
Mohammad Mehedi Hasan - avatar
0
Hoh Shen Yien What if instead of replacing the 1st element with 2nd element, I set every element to NULL?
16th Apr 2021, 9:15 AM
Mohammad Mehedi Hasan
Mohammad Mehedi Hasan - avatar
0
If setting every element to Null, you have reset the queue to an empty queue
16th Apr 2021, 9:24 AM
Hoh Shen Yien
Hoh Shen Yien - avatar