2017-11-11 173 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