循环队列错误修复+改进批注

时间:2019-09-07 18:53:54

标签: c++ software-design circular-buffer

在显示功能中可以清楚地看到这个问题。我想在顶部显示数组项,但是由于不断增加,我想不出办法。

Instead of this...:
void CircularQueue :: Display() const {
    for(int i = front; i < MAX; i++) {
        cout << a[i] << endl;
    }
}
**I want to display the circular queue using top:**
void CircularQueue :: Display() const {
    for(int i = front; i < top; i++) {
        cout << a[i] << endl;
    }
}

在我的主要职能中,我排队15个商品,结果,顶部增加了15次。因此,显然会有5个垃圾值。如何操作top以便显示功能显示所有10个数组值?


#include <iostream>
using namespace std;
#define MAX 10

class CircularQueue {
    private:    
        int top;
        int front;
    public:
        //assume that the max number of items in this circular queue is 10.
        int a[MAX]; 
        CircularQueue() {top = -1; front = -1;}
        int enqueue(int x);
        void dequeue();
        void peekFront() const;
        void peekBack() const;
        void Display() const;
        bool isEmpty();

};
//1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
//10,11,12,13,14,15,6,7,8,9

int CircularQueue :: enqueue(int x) {
    //Problem: The array is actually growing in size. 
    ++top;
    a[top%10] = x;   
    int y = a[top%10];
    cout << "Adding " << y << " to the queue." << endl; 
    if(top == 0) {
        front = 0;
    }
    return y;
}

void CircularQueue :: dequeue() {
    if(top < 0) {
        cout << "The queue is empty." << endl;
    } else {
        int x = a[top];
        cout << x << " will now be removed." << endl;
        for(int i = 0; i <= top - 1; i++) {
            a[i] = a[i+1];
        }
        top--;
        x = a[top];
        cout << "The last element of the queue is now: " << x << endl;
    }
}

bool CircularQueue :: isEmpty() {
    return top < 0;
}

void CircularQueue :: peekFront() const {
    if(front < 0) {
        cout << "The queue is empty." << endl;
    } else {
        int x = a[front];
        cout << "The Front value is: " << x << endl;
    }
}

void CircularQueue :: peekBack() const {
    if(top < 0) {
        cout << "The queue is empty." << endl;
    } else {
        int x;
        x = a[top];
        cout << "The back value is: " << a[top] << endl;
    }
}

void CircularQueue :: Display() const {
    for(int i = front; i < MAX; i++) {
        cout << a[i] << endl;
    }
}

int main() {
    CircularQueue Aq;
    Aq.enqueue(0); 
    Aq.enqueue(1); 
    Aq.enqueue(2); 
    Aq.enqueue(3);
    Aq.enqueue(4); 
    Aq.enqueue(5); 
    Aq.enqueue(6); 
    Aq.enqueue(7); 
    Aq.enqueue(8); 
    Aq.enqueue(9); Aq.Display();

    Aq.enqueue(10);
    Aq.enqueue(11);
    Aq.enqueue(12);
    Aq.enqueue(13);
    Aq.enqueue(14);
    Aq.enqueue(15); Aq.Display();


    return 0;
}

预期输出应为: 10,11,12,13,14,15,6,7,8,9

数组大小应始终为10。但是当我不断排队时;数组大小超过10。

0 个答案:

没有答案