不工作的单个链表C

时间:2016-12-11 14:52:43

标签: c list pointers

我现在太糟糕了。我的清单不起作用!我知道有一个问题就是将我的ptr应用到功能中,而不是实际使用真实的,但我无法理解如何才能按照我的意愿来完成这项工作。

PS。我也看到,如果我把头脑作为全球价值,那就没关系了。但我想获得功能,我可以将其称为特定列表。

这是将元素添加到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;
}

3 个答案:

答案 0 :(得分:0)

如果您没有将head的地址传递给该函数,您认为它是如何工作的?

正确代码:
add(20,&head)

你还必须改变你的功能签名:
void add(int num, struct node **head)

另外,要引用struct node指针,再次在add功能中,您想要head更改*head**head

请注意:*head指向head,因此每当您要对指针应用更改(而不是双指针*head时,您有使用xcodebuild -exportArchive -exportOptionsPlist app.plist -archivePath app.xcarchive -exportPath app.ipa 将其告诉编译器。

答案 1 :(得分:0)

您对它的期望如何?它不会工作,除非你传递指针head本身,这里你只是创建它的副本。你也可以这样做。

head = add(20,head);

而不仅仅是

add(20,head);

添加

return head;
在结束函数之前

并且不要忘记更改功能的返回类型

struct node* add( int num,struct node *head)

更新的代码如下所示

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

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

struct node* add( int num,struct node *head)
{
    struct node *temp;
    temp=malloc(sizeof(struct node));
    temp->data=num;
    if (head==NULL)
    {
        head=temp;
        head->next=NULL;
    }
    else
    {
        // please change your logic
    }
    return head;
}

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

    return 0;
}

干杯!

答案 2 :(得分: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的逻辑。