Note that there are some explanatory texts on larger screens.

plurals
  1. POQueue using Array>>shifting elements after popping
    primarykey
    data
    text
    <p>I'm trying to implement a queue using an array. Here is my code:</p> <pre><code>#include &lt;iostream.h&gt; #define SIZE 5 class queue { int *Queue, front, rear; public: queue() { Queue = new int[SIZE]; front = rear = -1; } void push() { if (rear == (SIZE-1)) { cout&lt;&lt;"\n Overflow!"; } else { rear++; cout&lt;&lt;"\n Enter element: "; cin&gt;&gt;Queue[rear]; } } void pop() { if (front == rear) { cout&lt;&lt;"\n Underflow!"; } else { cout&lt;&lt;"\nElement popped: "&lt;&lt;Queue[++front]; } } void display() { if (front == rear) { cout&lt;&lt;"\n Queue Empty"; } else { for(int i = (front+1); i&lt;=rear; i++) { cout&lt;&lt;Queue[i]&lt;&lt;" "; } } } }; int main() { int choice; queue q; while(choice != 4) { cout&lt;&lt;"\n\n Enter your choice :" &lt;&lt;"\n 1. Push an element into Queue." &lt;&lt;"\n 2. Pop an element from Queue." &lt;&lt;"\n 3. Display the Queue." &lt;&lt;"\n 4. Exit the program.\n\n"; cin&gt;&gt;choice; switch (choice) { case 1: q.push(); break; case 2: q.pop(); break; case 3: q.display(); break; case 4: break; } } return 0; } </code></pre> <p>The thing is that once the overflow is met, even after popping an element the rear remains the same and another element is not added when there is a vacant space where it can go.</p> <p>The solution for this could be to shift every element one place ahead so that there is empty spot at the end but I am having trouble with the shift. Also, if I try inserting after popping 2-3 times before reaching overflow then it still gives overflow even when there are only 3 elements in the queue. How can I solve this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload