在链表中,使用双指针和仅全局声明头指针哪个更好
//此处将头双指针作为参数传递
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;
}
}发布于 2015-03-30 23:42:54
我认为两者都不是:
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;
}
}
}我不知道你为什么要把地址改成函数中的头指针,这样就没有理由把它作为指针来传递了。
通常,良好的编程实践总是不鼓励使用全局变量,正如您在以下示例中所看到的:
发布于 2015-03-31 01:22:34
双指针版本可以简化为:
Void insertatend(node **head, int item)
{
node *ptr;
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
ptr->next=NULL;
while(*head!=NULL)
head = &((*head)->next);
*head = ptr;
}https://stackoverflow.com/questions/29350420
复制相似问题