簡體   English   中英

無法工作的單個鏈表C

[英]Not working single linked list C

我現在太糟了。 我的清單不起作用! 我知道存在一個問題,就是僅將我的ptr轉換為功能,而不是實際使用真正的ptr,但是我無法理解如何根據需要進行這項工作。

PS。 我還看到,如果我以全球價值為先,那沒關系。 但是我想獲得功能,可以將其稱為特定列表。

這是將元素添加到空白列表的功能。 我什至無法使此功能正常工作。 我嘗試過使用雙指針,但是現在我在這里尋求幫助。

   #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;
}

如果不將head地址傳遞給函數,您如何期望它會起作用?

正確的代碼:
add(20,&head)

而且,您還必須使用以下命令更改函數簽名:
void add(int num, struct node **head)

此外,參考你的struct node的指針,再add你要改變功能head*head

請注意: **head指向*head ,因此每次您要對指針(而不是雙指針head進行更改時,都必須使用*head將其告知編譯器。

您期望它如何運作? 除非您傳遞指針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;
}

干杯!

更改

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的邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM