鱼C论坛

 找回密码
 立即注册
查看: 261|回复: 1

队列问题

[复制链接]
发表于 2023-12-5 18:22:29 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include<stdio.h>
#include<stdlib.h>

#define MAX_SIZE 10

typedef struct{
        int items[MAX_SIZE];
        int front;
        int rear;
}Queue;

void initialize(Queue* queue)
{
        queue->front=-1;
        queue->rear=-1;
}

void enqueue(Queue* queue,int item)
{
        if(queue->rear==MAX_SIZE-1)
        {
                printf("队列已满,无法入队。\n");
        }
        else
        {
                if(queue->front==-1)
                {
                        queue->front=0;
                }
                queue->items[++(queue->rear)]=item;
        }
}

int dequeue(Queue* queue)
{
        if(queue->front==-1)
        {
                printf("队列为空,无法出队。\n");
                return -1;
        }
        else
        {
                int item=queue->items[queue->front];
                if(queue->front=queue->rear)
                {
                        queue->front=queue->rear=-1;
                }
                else
                {
                        (queue->front)++;
                }
                return item;
        }
}
int main()
{
        Queue queue;
        initialize(&queue);
       
        enqueue(&queue,1);
        enqueue(&queue,2);
        enqueue(&queue,3);
       
        printf("出队:%d\n",dequeue(&queue));
        printf("出队:%d\n",dequeue(&queue));
       
        return 0;
}

为什么输出为
出队:1
队列为空,无法出队。
出队:-1
跟计划的输出不一样呀
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-12-5 18:23:01 | 显示全部楼层
问题出在enqueue函数中的代码逻辑上。在enqueue函数中,将item赋值给queue->items,这是错误的。应该是将item存储在队列数组中的rear对应的位置。

修改enqueue函数如下:
  1. void enqueue(Queue* queue, int item)
  2. {
  3.     if (queue->rear == MAX_SIZE - 1)
  4.     {
  5.         printf("队列已满,无法入队。\n");
  6.     }
  7.     else
  8.     {
  9.         if (queue->front == -1)
  10.         {
  11.             queue->front = 0;
  12.         }
  13.         (queue->rear)++;
  14.         queue->items[queue->rear] = item;
  15.     }
  16. }
复制代码

另外,在dequeue函数中,判断队列是否为空的条件有问题。应该是`if (queue->front == -1 || queue->front > queue->rear)`,而不是`if (queue->front == -1)`。

修改dequeue函数如下:
  1. int dequeue(Queue* queue)
  2. {
  3.     if (queue->front == -1 || queue->front > queue->rear)
  4.     {
  5.         printf("队列为空,无法出队。\n");
  6.         return -1;
  7.     }
  8.     else
  9.     {
  10.         int item = queue->items[queue->front];
  11.         (queue->front)++;
  12.         return item;
  13.     }
  14. }
复制代码

修改完成后,输出结果将与您预期一致。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 21:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表