gpt4 book ai didi

c - 在链表的末尾插入一个节点

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:52 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <conio.h>

struct node
{
int data;
struct node* next;
};

int main()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;

head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));

head->data = 1;
head->next = second;

second->data = 2;
second->next = third;

third->data = 3;
third->next = NULL;

struct node* new1;
struct node* temp1;

temp1 = head;

while(temp1->next != NULL)
{
temp1 = temp1->next;
}

new1 = (struct node*)malloc(sizeof(struct node));

temp1->next = new1;
new1->data = 5;
new1->next = NULL;

while(temp1 != NULL)
{
printf("%d ",temp1->data);
temp1 = temp1->next;
}

return 0;
}

这是在链表末尾插入节点的程序。预期输出为 = 1 2 3 5,这里 5 是新节点的值。但是现在的输出是= 3 5。不知道我哪里错了。任何答案将不胜感激。

最佳答案

while(temp1->next != NULL)
{
temp1 = temp1->next;
}

在此循环之后,您的 temp1 位于列表的末尾,您将在列表的末尾添加一个节点。

现在您正在尝试从 temp1 进行打印,显然您只会得到 2 个节点,新节点和它之前的节点。如果你想从 head 打印整个列表。添加新节点后打印之前。将 temp1 指向头部。

temp1 = head;
while(temp1 != NULL)
{
printf("%d ",temp1->data);
temp1 = temp1->next;
}

关于c - 在链表的末尾插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27407247/

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