c - 不工作单链表 C

标签 c list pointers

我现在很糟糕。我的 list 不起作用!我知道存在一个问题,就是将我的 ptr 处理为函数,而不是实际使用真正的函数,但我不明白如何才能按照我的意愿完成这项工作。

PS。我还看到,如果我将头脑作为全局值(value),那就没问题了。但我想要获得函数,我可以将其称为特定列表。

这里是向 blamk 列表添加元素的函数。我连这个功能都无法工作。我尝试使用双指针,但现在我来这里寻求帮助。

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

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

void add( int num,struct node * head )
{
    struct node *temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    if (head== NULL)
    {
    head=temp;
    head->next=NULL;
    }
    else
    {
    temp->next=head;
    head=temp;
    }
}

int  main()
{
    struct node *head;
    head=NULL;
    add(20,head);
    if(head==NULL) printf("List is Empty\n");

    return 0;
}

UPD:我自己使用双指针的方法:

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

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

void add( int num, struct node **head )
{
    struct node **temp;
    temp=(struct node **)malloc(sizeof(struct node*));
    (*temp)->data=num;
    if (*head== NULL)
    {
    *head=*temp;
    (*head)->next=NULL;
    }
        else
{
(*temp)->next=head;
*head=temp;
}

}

int  main()
{
    struct node *head;
    head=NULL;
    add(20,&head);
    if(head==NULL) printf("List is Empty\n");

    return 0;
}

最佳答案

改变

struct node **temp;
temp=(struct node **)malloc(sizeof(struct node*));
(*temp)->data=num;
if (*head== NULL)
{
    *head=*temp;
    (*head)->next=NULL;
}

struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
(temp)->data=num;
if (*head== NULL)
{
    *head=temp;
    (*head)->next=NULL;
}

您遇到段错误的原因是因为在 malloc 中,您分配了 sizeof(struct node*),这对于指针来说基本上是足够的大小,并且没有任何意义所以。

另外,如果您计划添加更多节点,请更改 add 中 else 的逻辑。

关于c - 不工作单链表 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41087452/

相关文章:

Python - 加快列表排列的生成(以及检查 Dict 中是否排列的过程)

c++ - 关于数组指针的问题?

c++ - 如何创建变量数组 Arduino

c++ - 无法从 char*[] 转换为 char**

arrays - 在 C 中实现 memset 以设置整个字而不是逐字节设置

c - Valgrind 在 C 中设置空字节错误

python:比较2个实例列表

python - 基于子列表中的字母数字字符串的列表列表的自然排序?

c - 指针数组分配

C 数组分区