c - 如何在末尾添加节点(单链表)

标签 c

void addToEnd()
{
    newnode = (struct node*)malloc(sizeof(struct node));

    printf ("Enter the customer name :");
    scanf ("%s", newnode->cName);

    printf ("\nEnter customer number :");
    scanf ("%d", &newnode->cNumber);

    printf ("\nEnter transaction description :");
    scanf ("%s", newnode->tDescrip);

    newnode->next = NULL;
    if(list==NULL)
        list = newnode;
    else if (list != NULL && newnode < list)
    {
        newnode->next = list;
        list = newnode;
    }
    else
    {
        temp = list;
        while (temp != NULL)
        {
            if (newnode > temp)
            {
                prev = temp;
                temp = temp->next;
            }
        }
        newnode->next = prev->next;
        prev->next = newnode;
    }
}

我尝试了这段代码,但该代码只是添加到开始而不是结束,我该如何将节点添加到末尾?

最佳答案

我们看看下面的内容是不是那么容易理解。

只需更改指针:

struct node** tail = &list;
while (*tail != NULL) {
    tail = &((*tail)->next);
}
*tail = newnode;

关于c - 如何在末尾添加节点(单链表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9043395/

相关文章:

c++ - 在c中后台运行线程

c - 具有单独的参数(对于函数)或参数结构有什么区别?

c - 在 C 中实现 Miller-Rabin

CS50积分: how to change those if else conditions

c++ - 在文件中搜索一个单词并在 C 中替换它?

c - Android NDK - 如何函数调用另一个预建库

c++ - 多线程程序只执行最后创建的线程?

android - 在gstreamer管道中使用encodebin

c - openssl 没有正确验证签名

c - scanf 函数、说明符 %s 和新行