gpt4 book ai didi

C语言中构造指针链表

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

如果我在 main 中初始化列表,它的工作方式就像魅力,但我无法添加到空列表。为什么不呢?

#include "stdio.h"
#include "stdlib.h"

struct liste{

int a;
struct liste *next;
};


void AddEnd( int val, struct liste* l )
{

struct liste *aux;
struct liste *n;

n=(struct liste*) malloc (sizeof(struct liste));
n->a = val;
n->next = NULL;

aux=l;
if(aux == NULL)
{
l=n;
}
else
{
while(aux->next != NULL)
aux=aux->next;
aux->next=n;
}

}

void DeleteHead(struct liste* l){

struct liste *aux=l;
if (aux!=NULL)
{

l=l->next;
free(aux);
}
}
void Print ( struct liste* l)

{
printf("the list contains: \n ");

while(l!=NULL)
{

printf("%d | ",l->a);
l = l->next;
}

}



void main() {

struct liste* nl;
AddEnd(9,nl);
AddEnd(8,nl);
AddEnd(7,nl);
DeleteHead(nl);

Print(nl);

}

最佳答案

由于 c 中的参数按值传递,因此对 struct liste * l 所做的更改不会反射(reflect)在 main 函数中。从 AddEnd 函数返回指向列表头部的指针,即

struct liste * AddEnd( int val, struct liste* l )
{
.....
if(aux == NULL)
{
*l=n;

}
else
{
while(aux->next != NULL)
aux=aux->next;
aux->next=n;
}
return l;

然后在主函数中

 nl = AddEnd(nl);

将指针传递到列表的头部

关于C语言中构造指针链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21534834/

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