我对队列有一些困惑。当我返回一个指向队列开头的指针时,如下面的代码所示,并使用
Q = enQ(Q)该函数工作正常。然而,我不明白为什么函数需要返回任何东西,因为指向队列的指针是在中更新的。当函数返回void时,为什么下面的代码看起来不起作用?
enQ(Q)代码:
// Adds item to queue
struct node* enQ(struct node* Q, int n){
struct node* last = Q;
struct node* new = malloc(sizeof(struct node));
new->data = n;
new->next = NULL;
if (!Q){
Q = new;
} else {
while (last->next){
last = last->next;
}
last->next = new;
}
return Q;
}发布于 2018-10-18 10:02:00
第一次调用enQ()时,它的指针为空,表示应该创建一个新队列。enQ()创建一个新节点并返回指向该节点的指针。
在随后的调用中,不需要返回值是正确的,因为它只返回传入的相同Q,但第一次确实需要返回值。如果没有它,调用enQ(NULL, i)将无法将新队列返回给调用者。
发布于 2018-10-18 11:13:08
不使用直通节点进入队列,应创建队列结构并传入enQ *
typedef struct Queue {
struct node* head;
} Queue;
// Adds item to queue
void enQ(struct Queue* Q, int n) {
struct node* tail;
struct node* new = malloc(sizeof(struct node));
new->data = n;
new->next = NULL;
if (Q->head == NULL) {
Q->head = new;
} else {
tail = Q->head;
while (tail->next) {
tail = tail->next;
}
tail->next = new;
}
}
void deQ(struct Queue* Q, int n) {
if (Q->head == NULL) {
return;
}
struct node* temp = Q->head;
Q->head = Q->head->next;
free(temp);
}https://stackoverflow.com/questions/52865805
复制相似问题