-1

My realization of queue works in a strange way: when I enqueue new elements - all is right, but when I start to dequeue - it removes the last added element despite the fact that at this moment my head is 1 and tail is bigger. What are the pecularities of indexing in C++? Why does it behave like this? Here is my full code: https://hastebin.com/odibusacuk.cpp

class Queue{
public:
int head=1;
int tail=1;
int q[MAX];

int Queue::enqueue(int x){
    if (isFull()){
        return 0;}
    else {
        q[tail]=x;
       cout << tail << " here is a tail\n";
        if (tail==sizeof(q)){
            cout << tail << " this is tail\n" ;
            tail=1;}
        else {
            tail=tail+1;
            }
        return x;
        }
}
int Queue::dequeue(){
if(isEmpty()){
    cout << " the queue is empty\n";
    return 0;}
else {
    int x=q[head];
    if (head==sizeof(q)){
        head=1;}
    else {
        head=head++;
return x;}
    }
return 0;
}

1 Answers1

0

The problem you are having is because when you do something like

cout << k.enqueue(4) << " " << k.enqueue(9)  << ' ' << k.enqueue(6) << " " << k.enqueue(3) << " enqueued\n ";

it is not specified in what order these functions will be called. In your example, they are being called from right to left. This means your queue is actually

{ 0, 3, 6, 9, 4 }

0 is there since your are skipping element 0 and going directly to element 1. Your head is pointing to 1, thus you will dequeue 3.

You can read more here.

super
  • 9,722
  • 2
  • 13
  • 25