gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:26:28 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com