gpt4 book ai didi

c - 更好的链表编程实践

转载 作者:行者123 更新时间:2023-11-30 17:17:49 25 4
gpt4 key购买 nike

在链表中,使用双指针或仅全局声明头指针哪个编程更好

//这里头双指针作为参数传递

Void insertatend(node **head, int item)
{
node *ptr, *loc;
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
ptr->next=NULL;
if(*head==NULL)
*head=ptr;
else
{
loc=*head;
while (loc->next!=NULL)
{
loc=loc->next;
loc->next=ptr;
}
}

}

或者这个

//这里我已经将头指针声明为全局的

void insert(int x)
{
node *ptr,*ptr1;
ptr=(node*)malloc(sizeof(node));
ptr->info=x;
if(head==NULL)
{
ptr->next=head;
head=ptr;
}
else
{
ptr1=head;
while(ptr1->next!=NULL)
{
ptr1=ptr1->next;
}
ptr1->next=ptr;
ptr->next=NULL;
}
}

最佳答案

我不会说:

void insertatend(node *head, int item)
{
node *ptr, *loc;
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
ptr->next=NULL;
if(head==NULL)
head=ptr;
else
{
loc=head;
while (loc->next!=NULL)
{
loc=loc->next;
loc->next=ptr;
}
}

}

我不知道为什么您想要将地址更改为函数内的头指针,因此没有理由将其作为指针传递。

一般来说,良好的编程实践总是会阻止全局变量,正如您在这些示例中看到的:
Are global variables bad?
Why are global variables evil?
When is it ok to use a global variable in C?

关于c - 更好的链表编程实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350420/

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