【发布时间】:2021-06-04 07:26:36
【问题描述】:
是否可以像这样将链表的头部传递两次?这适用于代码块,但不适用于在终端中编译时。我首先将 head 的地址传递给 test(),然后传递给 append()。我是完全迷路了还是有可能?
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void append(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) last = last->next;
last->next = new_node;
return;
}
void printList(struct Node* node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
void test(struct Node* p) { append(p, 6); }
int main() {
struct Node* head = NULL;
test(&head);
// append(&head, 6);
printList(head);
return 0;
}
【问题讨论】:
-
我想这段代码在编译时会产生许多警告和错误。例如,
test()的参数类型不正确。 -
另外,请描述它是如何“不起作用”的。它会导致您的计算机着火吗?
-
接近一个错字:
test应声明为void test(struct Node** p) { append(p, 6); },因为它获取并传递Node **而不是Node *。间接级别很重要...
标签: c linked-list pass-by-reference singly-linked-list function-definition