gpt4 book ai didi

c - 使用函数插入到C中的单链表中不起作用

转载 作者:行者123 更新时间:2023-11-30 15:35:58 24 4
gpt4 key购买 nike

我试图用 C 创建一个单链表,不幸的是出了问题。这是我的代码:

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

int size,i;

struct list
{
int val;
struct list *next;
};
typedef struct list element;

void add(element *head, int value)
{
element *current;
current = (element*) malloc(sizeof(element));
current->val = value;
current->next = head;
head = current;
}

void displayList(element *first)
{
element *curr = first;
while (curr != NULL)
{
printf("%d",curr->val);
curr = curr->next;
}
}

int main()
{
element *head, *curr;
head = NULL;

/* This works fine, although I would like to insert this into a function add
curr = (element*) malloc(sizeof(element));
curr->val = 65;
curr->next = head;
head = curr;
*/

add(head, 15); ////Function add doesn't work, although the code is same as above
displayList(head);
}

现在我只想向列表中添加一个数字,看看它是否可以使用添加函数工作。注释部分工作正常,程序返回“65”,直到我将其放入函数中。当我尝试使用 add 函数时,结果是“进程返回 0 (0x0)”,仅此而已。我认为传递列表头来添加函数有问题,但我找不到任何错误。

最佳答案

/*你的问题是添加新节点后头指针没有得到更新的值,因为你在main中声明了头指针并在add函数中更新了局部变量head */

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

int size,i;

struct list
{
int val;
struct list *next;
};

typedef 结构列表元素; 元素 *head,curr;*
void add(元素 *h, int 值) { 元素当前; 当前 = (元素) malloc(sizeof(元素)); 当前->val = 值; 当前->下一个 = h; 头=当前;

   }

void displayList(element *first)
{
element *curr = first;
while (curr != NULL)
{
printf("%d",curr->val);
curr = curr->next;
}
}

int main()
{

head = NULL;

/* This works fine, although I would like to insert this into a function add
curr = (element*) malloc(sizeof(element));
curr->val = 65;
curr->next = head;
head = curr;
*/

add(head,15);
add(head,34); ////Function add doesn't work, although the code is same as above
displayList(head);
}

关于c - 使用函数插入到C中的单链表中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745934/

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