【问题标题】:Linked List queue [pop function]链表队列[pop函数]
【发布时间】:2016-04-18 17:57:57
【问题描述】:

我正在尝试制作一个从队列中弹出元素的函数

/**
 * This function extracts from the queue the patient with maximum priority
 * @param queue is the extraction point
 * @return the patient with maximum priority or a Patient type value with all the fields 0 if the queue is empty
 */

struct Patient priorityQueuePop(struct PriorityQueue *queue);

结构 PriorityQueue 是这样的:

struct PriorityQueue{
    unsigned size;
    struct PriorityQueue *next;
    struct PriorityQueue *front;
    struct PriorityQueue *rear;
}

病人是这样的:

enum Gender {
    MALE = 'M',
    FEMALE = 'F'
};

struct Patient {
    char firstName[20];
    char lastName[20];
    unsigned char age;
    enum Gender gender;
};

我试着做这样的事情:

struct Patient priorityQueuePop(struct PriorityQueue *queue){

struct Patient *item =(struct Patient*)malloc(sizeof(struct Patient));

    queue->front = queue->front->next;
    queue->size--;

return item;
}

但是我编译的时候报错:

priorityQueue.c:72:2: error: incompatible types when returning type ‘struct Patient *’ but ‘struct Patient’ was expected
return item;

有人能解释一下这应该怎么做吗? 谢谢

【问题讨论】:

  • 问题出在哪里?
  • 您的结构看起来不正确。 PriorityQueue结构体包含指向每个节点头尾的指针,PriorityQueuePatient结构体之间没有关系。
  • 错误信息不言自明:您的priorityQueuePop 函数声明它返回struct Patient,但您返回的item 类型为struct Patient *
  • 你知道数据指针和数据本身的区别吗?如果没有,您可以先学习 C 基础知识。
  • 应该是struct Patient* priorityQueuePop()

标签: c list queue


【解决方案1】:

假设您的 pop 函数具有正确的签名。

struct Patient priorityQueuePop(struct PriorityQueue *queue);

这表示函数priorityQueuePop 应该返回一个struct Patient。这与struct Patient * 不同。

struct Patient a_patient;
struct Patient *a_pointer_to_a_patient;

如何返回结构?您不需要动态分配它。

struct Patient
priorityQueuePop(struct PriorityQueue *queue)
{
    struct Patient patient;
    struct PriorityQueue *item;

    item = queue->front
    queue->front = queue->front->next;
    queue->size -= 1;
    if (queue->size == 0) {
        queue->front = queue->rear = queue->next = NULL;
    }
    item->front = item->rear = item->next = NULL;
    populatePatientFromItem(&patient, item);
    priorityQueueDestroy(item);

    return patient;
}

请注意,虽然将优先级队列的 cdr 视为优先级队列在理论上是正确的,但在这种情况下它是多余的,因为您的接口似乎没有在如何利用它。

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 2023-03-20
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多