【发布时间】:2021-05-20 22:34:22
【问题描述】:
这是我的链表代码的一部分:
struct node {
float data;
int key;
struct node* next;
};
typedef struct{
struct node *head;
struct node *current;
int length;
} linked_list;
linked_list *init_list(){
linked_list *out = malloc(sizeof(linked_list));
struct node *head = NULL;
struct node *current = NULL;
out->head = head;
out->current = current;
out->length = 0;
return out;
}
void push_core(struct node *head, int key, float data){
struct node *link = malloc(sizeof(struct node));
link->data = data;
link->key = key;
link->next = head;
// readjust to point at the new first node
head = link;
printf("%f; ", head->data);
}
void push(linked_list *list, int key, float data){
push_core(list->head, key, data);
list->length ++;
}
void print_list_core(struct node *head){
struct node* ptr = head;
printf("\n[");
while(ptr != NULL){
printf("(%d,%f)", ptr->key, ptr->data);
ptr = ptr->next;
}
}
void print_list(linked_list *list){
print_list_core(list->head);
}
但总的来说,在我初始化链表结构后,我无法使用 push() 来链接新指针,这是为什么呢?
linked_list *S = init_list();
for (int i = 0; i < n; i++)
{
push(S,i,0);
print_list(S);
printf("%d;", S->length);
}
为了澄清,列表的长度确实会正确更新。但是当我尝试打印列表时它不起作用。此外,有趣的是,当我最初只使用节点结构并为 head 和 current 定义全局变量时,在另一个文件中,代码工作正常。但是当我尝试将它们封装在这个 linked_list 结构中时,事情并没有按预期工作。
【问题讨论】:
-
C 语言按值传递函数参数。所以更新
push_core中的head不会对list结构中的head指针做任何事情。 -
@user3386109 我以为我传递了一个指针,所以它应该写在上面?那么我应该如何编辑代码以使其工作?我应该将其更改为双指针吗?谢谢!
-
你能调试你的代码吗?
-
如果我在写代码,我会去掉
push_core和print_list_core函数,只实现push和print_list。 -
我并不是要粗鲁,但是您应该使用调试器研究很多问题
标签: c data-structures linked-list