循环队列.检查是否已满 [英] Circular Queue. Checking if it's full or not

查看:61
本文介绍了循环队列.检查是否已满的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在检查循环队列是否已满时遇到问题.队列的最大大小设置为5.但是,在放入4个元素之后,不允许我添加第五个元素.我被卡住了.

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.

控制台输出

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);
    }
}

推荐答案

您的队列有五个元素,后方可以指向它们中的任何一个.因此,front也可以指向五个元素中的任何一个,从而指示五个状态.但是,如果您希望队列包含0、1、2、3、4或5个项目,则需要区分六个不同的状态.您正在尝试将6羽鸽子放入5个鸽子洞中.

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.

要使循环队列工作,您有三个选择:(1)添加空"或满"标志以区分这两种状态;(2)添加一个填充计数",该计数也可用于该目的;或(3)辞职,以免将N-1个项目放入N-1个队列中.

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.

这篇关于循环队列.检查是否已满的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆