2017-04-13 7 views
-1

リンクされたリストの最後に要素を追加できません。私は他の質問を探してみましたが、解決策を見つけることができません。Cのリンクリストの最後に要素を追加できません

コードは次のとおりです。

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

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

void PushE(struct node** head,int data); 

int main(){ 

    struct node* a = NULL; 
    PushE(&a,3); 
    PushE(&a,4); 
} 

void PushE(struct node** headRef, int data){ 


    struct node* current = *headRef; 
    struct node* nNode; 
    nNode = (struct node*)malloc(sizeof(struct node)); 
    nNode->data = data; 
    nNode->next= NULL; 

    if(current == NULL) 
    current = nNode; 
    else{ 
    while(current->next != NULL) 
     current = current->next; 

    current->next = nNode; 
    } 

} 

誰も私がこれを実装するのに役立つことができます。

+0

を定義することができ、[C ' 'に'のmalloc() 'と家族の戻り値をキャストさせない理由でこの議論を参照してください。](HTTP: //stackoverflow.com/q/605845/2173917)。 –

+1

'struct node'はどこに定義されていますか? –

+0

私はコピー貼り付けがどのようにステートメントの真ん中から何か......... ...を変えるのだろうか –

答えて

4

問題はここにある:

if(current == NULL) 
    current = nNode; // <-- 

あなたが現在入手ましたか?ここ

struct node* current = *headRef; 

現在はheadRefが指さポインタのコピーです!

*headRefに直接割り当てる必要があります。この中

+0

ありがとう、Aconcagua、 –

1

声明

if(current == NULL) 
    current = nNode; 

変更ローカル変数電流が存在する場合。ヘッドが指すポインタは変更されません。したがって、元のリストは関数を終了した後も変更されません。

関数が宣言され、次のよう

int PushE(struct node ** head, int data); 

// ... 

int PushE(struct node ** head, int data) 
{ 
    struct node *nNode = malloc(sizeof(struct node)); 
    int success = nNode != NULL; 

    if (success) 
    { 
     nNode->data = data; 
     nNode->next = NULL; 

     while (*head) head = &(*head)->next; 

     *head = nNode; 
    } 

    return success; 
} 
関連する問題