0

I am learning about queues and I wrote the following program which implements the queue as a linear array (NOT a circular one).

   #include<iostream>
using namespace std;

class queue {
    int front, max_queue, rear, count = 0;
    int *items;
public:
    queue(int);
    ~queue();
    void enqueue(int);
    void dequeue();
    bool isEmpty();
    int size();
    void display();
};

queue::~queue() {
    delete []items;
}

queue::queue(int max) {
    front = -1;
    rear = -1;
    max_queue = max;

    items = new int[max_queue];
}

void queue::enqueue(int n) {
    if (count == max_queue)
        cout << "queue is full, no enqueue possible";
    else {
        items[++rear] = n;
        count++;
    }
}

void queue::dequeue() {
    if (count == 0)
        cout << "no dequeue possible, queue already empty";
    else {
        front--;
        count--;
    }
}

bool queue::isEmpty() {
    return ((count == 0) ? 1 : 0);
}

int queue::size() {
    return count;
}

void queue::display() {
    if (count == 0)
        cout << "nothing to display";
    else {
        for (int i = front; i <= rear;)
            cout << items[i++] << endl;
    }

}

int main() {

    queue *qe = new queue(10);

    qe->enqueue(1);
    qe->enqueue(2);
    qe->enqueue(3);
    qe->enqueue(4);
    qe->display();


    return 0;
}

I get the following output

49
1
2
3
4

RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms

Why is there a 49 in my output.? Is it a garbage value? Does not using a circular array implementation,a probable cause? I have no idea. Any help appreciated.

3 Answers 3

3

You're starting the display loop i with front which is -1. You're pointing to a spot before your queue.

Sign up to request clarification or add additional context in comments.

2 Comments

But wont front be -1 only when the queue is empty? If count!=0 then shouldn't front be equal to 0 or any higher value?
your enqueue function isn't updating front though
1

If a queue is empty and you enqueue an element x, then x becomes both the front and the rear.

Comments

0

The issue is in your display function:

for (int i = front; i <= rear;)
    cout << items[i++] << endl;

You're setting i=front, but you've previously set front=-1. Thus, you're attempting to access items[-1]. You can either set i=front+1:

for (int i = front + 1; i <= rear;)
    cout << items[i++] << endl;

or continue until i<rear and use ++i instead of i++:

for (int i = front; i < rear;)
    cout << items[++i] << endl;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.