这个循环队列永远不会让我队列满了,为什么?

问题描述 投票:-4回答:1

程序永远不会让我排队满满的,为什么?无论何时编译,它都会不断向队列中添加项目,即使它已满,也会被覆盖。虽然对我来说是一切逻辑,但每当我编译时,永远不会让队列达到tail = 4和head = 0这是isfull()函数的两个条件中的一个,所以为什么队列重置自己而不是给我那个它是满的!

#include<stdio.h>

#define MAX_QUEUE_SIZE 5

int head = -1, tail = -1;

void enqueue(int*, int*, int);
int dequeue(int*, int*);
int queue_is_empty(int*, int*);
int queue_is_full(void);
void display(void);

int queue[MAX_QUEUE_SIZE];

void main(void)
{
    dequeue(&tail, &head);
    enqueue(&tail, &head, 1);
    enqueue(&tail, &head, 2);
    enqueue(&tail, &head, 3);
    enqueue(&tail, &head, 4);
    display();
    enqueue(&tail, &head, 5);
    display();
    enqueue(&tail, &head, 6);
    display();
    enqueue(&tail, &head, 7);
    enqueue(&tail, &head, 8);
    display();
}

void enqueue(int* tailptr, int* headptr, int data)
{
    if (!(queue_is_full()))
    {
        if (*headptr == -1)
        {
            *headptr = 0;
        }
        (*tailptr) = (*tailptr + 1) % MAX_QUEUE_SIZE;
        queue[*tailptr] = data;
        printf("\nYou've inserted->\t%d", data);
    }
    else
    {
        printf("The queue is full\n");
    }
}

int dequeue(int* tailptr, int* headptr)
{
    if (!queue_is_empty(tailptr, headptr))
    {
        int data;
        data = queue[*headptr];
        if (*tailptr == *headptr)
        {
            *tailptr = -1;
            *headptr = -1;
        }
        else
        {
            (*headptr) = (*headptr + 1) % MAX_QUEUE_SIZE;
        }
        printf("\nYou've deleted->\t%d", data);
        return(data);
    }
    else
    {
        printf("The queue is empty\n");
    }
}

int queue_is_full(void)
{
    if ((tail + 1 == head) || (((head = 0) && (tail == MAX_QUEUE_SIZE - 1))))
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int queue_is_empty(int* tailptr, int* headptr)
{
    return ((*headptr) == -1) ? 1 : 0;
}

void display(void)
{
    int i;
    printf("\nHead->%d", head);
    printf("\tItems-> ");
    for (i = head; i != tail; i = (i + 1) % MAX_QUEUE_SIZE)
    {
        printf("%d\t", queue[i]);
    }
    printf("%d\t", queue[i]);
    printf("\tTail->%d", tail);
}
c
1个回答
0
投票

您的queue_is_full函数中有两个问题。以下是正确的版本。

int queue_is_full(void)
{
    if (((tail + 1) % MAX_QUEUE_SIZE == head) || (((head == 0) && (tail == MAX_QUEUE_SIZE - 1))))
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

问题是(tail + 1) % MAX_QUEUE_SIZE == headhead == 0(你只给了一个=

© www.soinside.com 2019 - 2024. All rights reserved.