队列实现C ++

时间:2017-11-11 18:27:25

标签: c++ indexing queue

我对队列的实现以一种奇怪的方式运作:当我将新元素排入队列时 - 一切都是正确的,但是当我开始出队时 - 它会移除最后添加的元素,尽管此时我的头部是1而尾部是大。 C ++中索引的特征是什么?为什么它会像这样? 这是我的完整代码: 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 个答案:

答案 0 :(得分:0)

您遇到的问题是因为当您执行

之类的操作时
cout << k.enqueue(4) << " " << k.enqueue(9)  << ' ' << k.enqueue(6) << " " << k.enqueue(3) << " enqueued\n ";

没有指定调用这些函数的顺序。 在您的示例中,它们是从右到左调用的。 这意味着您的队列实际上是

{ 0, 3, 6, 9, 4 }

0,因为您正在跳过元素0并直接转到元素1。 你的头指向1,因此你会出列3。

您可以阅读更多here