【发布时间】:2020-02-27 12:35:09
【问题描述】:
我正在尝试将“n”个节点添加到双循环链表的开头 这是添加节点的函数:
//the **head is assigned the address of the original head pointer which is being passed from the main function.
void insert(struct node**head,int n){
while(n-- >0){
int num;
//to input the data for the linked list
scanf("%d",&num);
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=num;
if(*head==NULL){
newnode->next=newnode;
newnode->prev=newnode;
*head=newnode;
}
else{
newnode->next=*head;
newnode->prev=(*head)->prev;
//to make the previously first node point to the new first node
newnode->next->prev=newnode;
//to make the last node point to the new first node
(*head)->prev->next=newnode;
*head=newnode;
}
}
}
当我执行它时,它没有显示任何输出但是当我改变时
//to make the last node point to the new first node
(*head)->prev->next=newnode;
这一行到
newnode->prev->next=newnode;
代码正在运行。 我无法理解这两种说法有什么区别。
【问题讨论】:
-
@virolino
*head非常有意义,因为这意味着head的更新值被传递给调用函数 -
@ChrisTurner:头脑风暴——
*head只有在head被定义为struct node** head之类的东西时才有意义——这太过分了。 -
@virolino 无需猜测 - 传入指向某事物的指针允许您对其进行更新,因为 C 仅通过值传递,并且是编写此类函数的两种方法之一
-
张贴
struct的声明,这一切都是基于。 (真的应该是minimal reproducible example以便更多的理解。) -
这并没有解决核心问题,但因为这是
C(而不是C++),所以声明:struct node* newnode=(struct node*)malloc(sizeof(struct node));将正确地写为struct node* newnode=malloc(sizeof(* newnode));。即it is not necessary or optimal to cast the return of malloc() in C.
标签: c circular-list