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

时间:2017-12-24 15:19:20

标签: c

程序永远不会让我排队满员,为什么?无论何时编译,它都会不断向队列中添加项目,即使它已满,也会被覆盖。 虽然对我来说是一切逻辑,但每当我编译时,永远不会让队列达到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);
}

1 个答案:

答案 0 :(得分:0)

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

[a-zA-Z]+

问题是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 == head(您只提供了一个head == 0