2017-11-11 182 views
-1

我对队列的实现以一种奇怪的方式工作:当我排队新元素时 - 一切正常,但是当我开始出队时 - 它删除最后添加的元素,尽管此时我的头是1尾巴更大。 C++中索引的用法是什么?为什么它的行为如此? 这里是我的全码: https://hastebin.com/odibusacuk.cpp队列实现C++

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; 
} 
+0

请包括[mcve]。 – hnefatl

+0

你需要告诉我们你做了什么,以便我们能够纠正它。 –

+0

我的输出是: 4 9 6 3入队 1头和尾巴5 3出队 –

回答

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