【问题标题】:Append an element at the end of a linked-List in C programming在 C 编程中的链表末尾附加一个元素
【发布时间】:2013-12-31 17:39:27
【问题描述】:

我一直在研究 C 中的链表,关于 append 函数,我遇到了以下代码:

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



void append(int num)
{
    struct node *temp,*right;
    temp= (struct node *)malloc(sizeof(struct node));
    temp->data=num;
    right=(struct node *)head;
    while(right->next != NULL){
       right=right->next;
    }
    right->next =temp;
    right=temp;
    right->next=NULL;
}

为了节省一行代码,是不是可以在temp下一个 属性?像这样:

void append(int num)
    {
        struct node *temp,*right;
        temp= (struct node *)malloc(sizeof(struct node));
        temp->data=num;
        temp -> next = NULL;
        right=(struct node *)head;
        while(right->next != NULL){
           right=right->next;
        }
        right->next =temp;
    }

【问题讨论】:

  • 这没什么问题。
  • 不能保证head 指向正确的列表。

标签: c null linked-list append


【解决方案1】:

是的,你是对的。事实上,我将通过编写如下分配和初始化数据的单独函数来进一步减少代码长度:

struct node * getnode(int date){
    struct node *temp = malloc(sizeof(struct node));
    temp->data = data;
    temp->next = NULL;
    return temp;
}

// assuming list have more than one elements: demo code 
void append(struct node *head, int num){
    struct node *right = head;
    while(right->next != NULL){
       right=right->next;
    }
    right->next = getnode(num);
}

此获取节点功能在代码的其他部分可能很有用,例如insertatfist()insert()

顺便说一句:Don't cast the returned address of malloc() and calloc().

可能你喜欢写struct node* getnode(int data, struct node* next) 函数来设置下一个节点地址。

称它为:

  • 插入最后一个节点:

    curt->next = getnode(num, NULL);
    
  • curt 节点和curt->next 之间插入。

    curt->next = getnode(num, curt->next);
    

【讨论】:

    【解决方案2】:

    以这种方式当然可以这样做,但是,我看到第一种方法中的代码在我看来更具可读性(非常小)。但是,您不会节省太多。

    但不要尝试对所有程序进行此类优化,让可读性比节省几行代码更重要。原因是编译器无论如何都会进行优化。

    【讨论】:

      【解决方案3】:

      如果你想“保存行”,你也可以使用 calloc,而不是 malloc,它会将你的字节归零, 但这不太清楚。

      它确实为您节省了一行代码,而且可以说更清晰。 我认为您提议的代码更改是一种改进,因为它将新节点的创建与放置它分开。

      如果这是生产代码,我可能会让睡狗撒谎。但是,虽然我们都在这里插话,但我将如何实现相同的功能。

      struct node
      {
          int data;
          struct node *next;
      };   
      
      struct node* init_node(int num)
      {
          struct node * temp = malloc(sizeof(struct node));
          temp->data = num;
          return temp;
      }
      
      void append(struct node* n, struct node* list)
      {
          while(list->next != NULL){
             list=list->next;
          }
          list->next =n;
          n->next=NULL;       
      }
      

      【讨论】:

      • Joshua 我想你想写 list->next init_node(num); 代替 list->next =n;
      • @GrijeshChauhan 不,我会把它们分开。调用代码将 init_node,然后 append()。对于 int 列表并没有太大区别,但代码将更好地移植到任何具有指向自身的 next 指针的结构。
      猜你喜欢
      • 1970-01-01
      • 2020-09-11
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多