Circular Queue. Checking if it's full or not

早过忘川 提交于 2020-12-15 06:44:06

问题


I'm having issue with checking if my circular queue is full or not. The maximum size for the queue is set to 5. However, after putting in 4 elements, it doesn't let me add a fifth element. I'm stuck.

Console output

void init (struct data* ptr) {
    ptr->rear = 0;
    ptr->front = 0;
}

void display (struct data* ptr) {
    if (empty(ptr)) {
        printf("\nNo data to display. The queue is EMPTY.\n");
    } else if (ptr->rear > ptr->front) {
        for (int i = ptr->front; i < ptr->rear; i++) {
            printf ("%d ", ptr->data[i]);
        }
    } else {
        for (int i = 0; i < ptr->rear; i++) {
            printf("%d ", ptr->data[i]);
        }
        for (int i = ptr->front; i < MAX; i++) {
            printf("%d ", ptr->data[i]);
        }
    }
    printf("\n");
}

bool empty (struct data* ptr) {
    if (ptr->rear == ptr->front) {
        return true;
    } else {
        return false;
    }
}

void enQueue (struct data* ptr, int input) {
    int nR = (ptr->rear + 1) % MAX;
    if (nR == ptr->front) {
        printf("\nQueue is FULL.\n\n");
    } else {
        ptr->data[ptr->rear] = input;
        ptr->rear = nR;
        printf("\nElement %d is inserted.\n\n", input);
    }
}

回答1:


Your queue has five elements, and rear can point to any of them. So front also can point to any of the five elements, and thus indicate five states. But if you want the queue to contain 0,1,2,3,4 or 5 items, that's six different states to distinguish. You're trying to put 6 pigeons into 5 pigeonholes.

To make a circular queue work, you have three choices: (1) add an "empty" or "full" flag to distinguish between those two states; (2) add a "fill count" which can also be used for that purpose; or (3) resign yourself to never putting more than N-1 items in your N-size queue.



来源:https://stackoverflow.com/questions/60086219/circular-queue-checking-if-its-full-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!