gpt4 book ai didi

C链表末尾插入节点

转载 作者:太空狗 更新时间:2023-10-29 16:53:07 25 4
gpt4 key购买 nike

我在使用 C 中的链表插入方法时遇到了一些问题。它似乎只在列表的开头添加。我做的任何其他插入都失败了。而且这个 CodeBlocks 调试器太难理解了,我还是不明白。它从不给我值(value),只是内存中的地址。不管怎样,这是我的职责。你看到它失败的任何原因了吗?

/* function to add a new node at the end of the list */
int addNodeBottom(int val, node *head){

//create new node
node *newNode = (node*)malloc(sizeof(node));

if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}

newNode->value = val;

//check for first insertion
if(head->next == NULL){
head->next = newNode;
printf("added at beginning\n");
}

else
{
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while(current->next != NULL)
{
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
}
current = current->next;
}
}
return 0;
}

然后在main中,只加了929。

   //testing addNodeBottom function
addNodeBottom(929, head);
addNodeBottom(98, head);
addNodeBottom(122, head);
addNodeBottom(11, head);
addNodeBottom(1034, head);

最佳答案

此代码将起作用。 samplebias 的答案几乎是正确的,但您需要第三次更改:

int addNodeBottom(int val, node *head){

//create new node
node *newNode = (node*)malloc(sizeof(node));

if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}

newNode->value = val;
newNode->next = NULL; // Change 1

//check for first insertion
if(head->next == NULL){
head->next = newNode;
printf("added at beginning\n");
}

else
{
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while (true) { // Change 2
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
break; // Change 3
}
current = current->next;
};
}
return 0;
}

更改 1:newNode->next 必须设置为 NULL,这样我们就不会在列表末尾插入无效指针。

变化2/3:循环改为无限循环,当我们找到最后一个元素时,用break;跳出。请注意 while(current->next != NULL) 与之前的 if(current->next == NULL) 是如何矛盾的。

编辑:关于 while 循环,这种方式要好得多:

  node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");

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

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