gpt4 book ai didi

c - 我无法将元素添加到 C 中链接列表的末尾

转载 作者:行者123 更新时间:2023-11-30 18:24:13 25 4
gpt4 key购买 nike

我无法将元素添加到单个链接列表的末尾。我尝试过寻找其他问题,但找不到解决方案。

代码是:

#include<stdio.h>
#include<stdlib.h>

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

void PushE(struct node** head,int data);

int main(){

struct node* a = NULL;
PushE(&a,3);
PushE(&a,4);
}

void PushE(struct node** headRef, int data){


struct node* current = *headRef;
struct node* nNode;
nNode = (struct node*)malloc(sizeof(struct node));
nNode->data = data;
nNode->next= NULL;

if(current == NULL)
current = nNode;
else{
while(current->next != NULL)
current = current->next;

current->next = nNode;
}

}

任何人都可以帮我实现这个吗?

最佳答案

问题出在这里:

if(current == NULL)
current = nNode; // <--

你是如何获得电流的?

struct node* current = *headRef;

这里当前是 headRef 指向的指针的副本!

您需要直接分配给*headRef

关于c - 我无法将元素添加到 C 中链接列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43386520/

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