gpt4 book ai didi

c - 我正在尝试从链接列表末尾的列表中添加数字

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

我正在尝试使用尾部从链表末尾的列表中添加数字,但我不明白为什么我的尾部永远不会改变。

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

typedef struct node NOD;
//I addd the first node
void addfirst(int num)
{
NOD *temp;//This is the new node
temp = (NOD*)malloc(sizeof(NOD));
temp->data = num;
temp->next = NULL;
head = tail = temp;
}
//I add at the end of the list
void add(int num)
{
NOD *temp;
temp = (NOD*)malloc(sizeof(NOD));
temp->data = num;
temp->next = NULL;
tail->next = temp;
tail = temp;
}

int main()
{
int n , num, i;
freopen("intrare.txt" , "r" , stdin);
scanf("%d" , &n);
for(i = 0 ; i < n ; i++)
{
scanf("%d" , &num);
if(i==1)
addfirst(num);
else
add(num);
}

return 0;
}

最佳答案

temp->data = num;
temp->next = NULL;
head = tail = temp;

将此代码更改为

temp->data = num;
temp->next = head;
head = temp;

在头部添加时无需更改尾部。另外,通过执行 head = tail = temp; 您将丢失之前创建的列表。

关于c - 我正在尝试从链接列表末尾的列表中添加数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40468379/

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