【问题标题】:Better programming practice in linked list链表中更好的编程实践
【发布时间】:2015-03-30 15:39:52
【问题描述】:

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

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

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;
     }
  }

【问题讨论】:

  • 顺便说一句 loc->next=ptr; insertatend 移动到while循环之后。

标签: c data-structures computer-science


【解决方案1】:

我都不会说:

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?

【讨论】:

    【解决方案2】:

    双指针版本可以简化:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2014-10-18
      • 2011-07-29
      • 1970-01-01
      相关资源
      最近更新 更多