c - 在 C 编程中的链表末尾追加一个元素

标签 c null linked-list append

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

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中添加NULL吗?/strong> 的 next 属性?像这样:

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

最佳答案

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

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

关于c - 在 C 编程中的链表末尾追加一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20861188/

相关文章:

c - 请解释一下这段C代码的for循环和输出

python - 在 Postgres 中存储 JSON 时保留 Python None/NULL

Java查看队列中的元素

c - malloc 应该被赋予指针大小或内存大小?

c - 指向结构的指针在每次函数调用时变为 NULL

C strcpy() - 邪恶?

arrays - 如何从数组末尾删除 nil 或空元素?

java - 从 Jar : Always null 加载图像

java - OutofMemory 链表添加错误

c - typedef 结构清晰度