我正在尝试创建一个从队列中弹出元素的函数
/**
* 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;
有人可以解释如何做到这一点吗? 谢谢
答案 0 :(得分:0)
假设你的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 也是优先级队列是正确的,但在这种情况下它是过度的,因为它看起来你的接口没有在利用它的方式。