【问题标题】:Checking if queue is empty检查队列是否为空
【发布时间】:2020-11-13 02:14:19
【问题描述】:

我是 C 新手,我正在尝试编写队列问题。目前,我正在编写一些代码来检查队列是否为空。这是我目前所拥有的:

对于 Queue.h(这是我们的讲师提供的)

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

struct queueNode {
    char data;
    struct queueNode *nextPtr;
};

typedef struct queueNode QueueNode;
typedef QueueNode* QueueNodePtr;

typedef struct Queue {
    QueueNodePtr head;
    QueueNodePtr tail;
} Queue;

void instructions();
int isEmpty(Queue);
void enqueue(Queue*, char);
char dequeue(Queue*);
void printQueue(Queue);
void freeQueue(Queue*);

对于 Queue.c

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

#include "Queue.h"

int isEmpty(struct Queue queue)
 {
     if (Queue == NULL)
     {
         return 1;
     }
 }

问题在 Queue.c 的第 8 行,编译器说“错误:'Queue' 之前的预期表达式”我将如何解决这个问题?

编辑:我尝试使用 queue == NULL 而不是 Queue == NULL 并且编译器说:错误:二进制操作数无效 ==(有 'struct队列'和'void*')。

非常感谢!

【问题讨论】:

  • Queue 是结构的名称。表达式Queue == NULL 试图将类型名称与值进行比较。参数struct Queue queue 通过value 传递您的队列,这可能不是您想要的。考虑到所有因素,绝对不清楚如何回答这个问题,因为它可能取决于您的结构本身的语义。我建议您编辑您的问题以显示Queue.h 的内容。
  • 阅读Modern C,查看C reference website,阅读编译器文档(例如GCC...)和调试器 (例如GDB)。使用 GCC 编译为 gcc -Wall -Wextra -g(所有警告和调试信息)。从github 上用 C 编码的现有程序中汲取灵感
  • 感谢您的参考!它们确实很有用!

标签: c queue


【解决方案1】:

首先,使用一致的方式传递您的队列。注意接口的区别:

int isEmpty(Queue);             //<-- by value
void enqueue(Queue*, char);     //<-- by reference
char dequeue(Queue*);           //<-- by reference
void printQueue(Queue);         //<-- by value
void freeQueue(Queue*);         //<-- by reference

其中一些通过值传递队列结构,而另一些通过引用(指针)传递。您可能希望所有函数都对指针进行操作, Queue*

接下来,您应该进行某种初始化队列的操作。你已经有freeQueue,它正好相反。所以你可能想要initQueue

void initQueue(Queue* q) {
    q->head = NULL;
    q->tail = NULL;
}

现在,进入实际问题...正如我已经建议的那样,您应该更改isEmpty(和printQueue)以接受指向队列的指针。然后你使用任何逻辑应该表明队列是空的。由于我在初始化时已在上面断言,head 指针可能应该为 NULL,那么这也将是一个适当的“空”测试:

int isEmpty(Queue* q) {
    return q->head == NULL;
}

最后,因为您可能会问如何实际使用它:

int main(void)
{
    Queue q;

    initQueue(&q);
    printf("Queue empty: %d\n", isEmpty(&q));

    enqueue(&q, 'X');
    printf("Queue empty: %d\n", isEmpty(&q));

    enqueue(&q, 'Y');
    enqueue(&q, 'Z');
    printQueue(&q);

    printf("Removed %c\n", dequeue(&q));
    printQueue(&q);

    freeQueue(&q);        
    return 0;
}

【讨论】:

  • 非常感谢!这很有帮助!
猜你喜欢
  • 1970-01-01
  • 2011-12-19
  • 2019-12-02
  • 1970-01-01
  • 2021-02-01
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
相关资源
最近更新 更多