gpt4 book ai didi

c++ - 链表中头/第一个节点的声明

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:10 25 4
gpt4 key购买 nike

大家好,我遇到了一个链表问题。给定两段代码,我必须找出其中一段代码无法正常工作的原因

代码1是

struct node {
int data;
struct node *link;
};

void insert(struct node *head) {
struct node *last, *temp;
head = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &head->data);
head->link = NULL;
last = head;
{
int n = 3;
while(n>0){
temp = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &temp->data);
temp->link = NULL;
last->link = temp;
last = temp;
n--;
}
}
return;
}

void display(struct node *p) {
while(p) {
printf("%d ",p->data);
p = p->link;
}
return;
}

int main() {
struct node *head;
insert(head);
display(head);
return 0;
}

第二个代码是

struct node {
int data;
struct node *link;
}*head;

void insert() {
struct node *last, *temp;
head = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &head->data);
head->link = NULL;
last = head;
{
int n = 3;
while(n>0){
temp = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &temp->data);
temp->link = NULL;
last->link = temp;
last = temp;
n--;
}
}
return;
}

void display(struct node *p) {
while(p) {
printf("%d ",p->data);
p = p->link;
}
return;
}

int main() {
insert();
display(head);
return 0;
}

现在我的问题是,为什么在第一个代码中的 main 中声明 head 没有为显示函数提供 o/p,而在第二个代码中全局声明它是有效的?问这个是因为我想知道在第一种情况下 head 在 main 中声明并作为地址传递所以从插入函数返回后它应该得到插入函数操作的效果但它不像那样工作并且没有给 Ant o/p 显示功能

最佳答案

问题在于,在第一个代码中,insert 接收到mainhead拷贝> 指针并通过使其指向一些新分配的内存来修改该拷贝。该修改永远不会传播回 main

要使其传播,请使用指向指针的指针:

void insert(struct node **head) {
struct node *last, *temp;
*head = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &(*head)->data);
(*head)->link = NULL;
last = *head;
{
int n = 3;
while(n>0){
temp = (struct node *)malloc(sizeof(struct node));
printf("Input an integer: ");
scanf("%d", &temp->data);
temp->link = NULL;
last->link = temp;
last = temp;
n--;
}
}
return;
}

然后,在 main 中,这样调用它:

insert(&head);

或者,您可以让 insert 接受一个指针,同时返回一个指针(即新的头):

struct node* insert(struct node *head) { ... }

该 API 的一个问题是它很容易出错:很容易调用 insert() 而忘记处理它的返回值。

关于c++ - 链表中头/第一个节点的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com