gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:38:26 27 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* temp;
temp = head;

while (temp != NULL) { // for printing the linked list
printf("%d ",temp->data);
temp = temp->next;
}

struct node* new1;
struct node* temp1;

temp1 = head;

while (temp1 != NULL) { // for traversing to the end
temp1 = temp1->next;
}

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

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

temp1->next = new1;

while (temp1 != NULL) { // again for printing the list
printf("%d ",temp1->data);
temp1 = temp1->next;
}

return 0;
}

我试图在链表的末尾插入一个节点,但它不起作用。我成功创建了链表,但无法在末尾插入节点。这是我的老师教我的,但行不通。

最佳答案

据我了解,在评论的部分

// for traversing to the end

实现迭代太多;条件应该是

while ( temp1->next != NULL )

在到达最后一个节点时立即终止,而不是在到达终止 NULL 指针时终止。

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

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