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/

10-11 16:34