2017-03-29 2 views
-1

リンクリストに挿入しようとしています。ここで私は同じのために書いたものです:リンク先リストのheadは常にヌルです。

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


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


void show_menu() 
{ 
    printf("\nWhat do you want to do: \n"); 
    printf("1.Insert \n2.Delete \n3.Show"); 
    printf("\nEnter your choice: \n"); 
} 

void insert(struct node *head) 
{ 
    int new_numer; 
    printf("Enter a number to insert in the linked list: \n"); 
    scanf("%d",&new_numer); 

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

     struct node *new_node = (struct node *)malloc(sizeof(struct node)); 

     new_node -> data = new_numer; 

     new_node -> next = NULL; 

     while(temp -> next != NULL) 
     { 
      temp = temp -> next; 
     } 
     temp->next = new_node; 
    } 
} 


void show(struct node *head) 
{ 
    printf("\n The elements in the list are: \n"); 
    while (head != NULL) 
    { 
     printf("%d\n", head->data); 
     head = head -> next; 
    } 
} 


int main(int argc, char const *argv[]) 
{ 
    int choice; 

    struct node *head = NULL; 


    while(1) 
    { 
     show_menu(); 
     scanf("%d",&choice); 

     switch(choice) 
     { 
      case 1: 
       insert(head); 
       show(head); 
      break; 

      case 2: 
       show(head); 
      break; 

      case 3: 
      break; 

      default: 
       printf("Don't fuck with me.\n"); 
     } 

    } 


    return 0; 
} 

コードを実行するには、私が得た:

What do you want to do: 
1.Insert 
2.Delete 
3.Show 
Enter your choice: 
1 
Enter a number to insert in the linked list: 
12 

The elements in the list are: 

What do you want to do: 
1.Insert 
2.Delete 
3.Show 
Enter your choice: 

リストに挿入された要素がないのはなぜ?

私は、main関数に

head = (struct node *)malloc(sizeof(struct node)); 

を移動していた場合は、私が挿入されたゼロおよびその他のような第1の要素を取得しています。

私はここで何が欠けていますか?

+0

頭に割り当てたnew_nodeを添付しませんか? – bruceg

+0

'insert()'は 'main()'から 'head'を変更することはできません。値によって渡されるからです。 – Dmitri

+0

[Cリンクされたリストの重複する可能性がありますなぜ私のリストの先頭の変数がnull(Cの新機能)のままです](http:// stackoverflow。 com/questions/20108412/c-linked-list-why-is-my-list-head-variable-remaining-null-new-to-c) –

答えて

2

あなたが直面している問題は、最初の要素を挿入しているときに、ヘッドが変化していないことです。値を関数に渡しました。

あなたがする必要があるのは、頭部のアドレス、つまりstruct node** headを渡してから、最初に挿入された要素の場合は*headに変更します。

+0

少し詳しく教えていただけますか? – learner

+0

したがって、メインではheadをNULLに設定しています。そして、それを挿入関数に渡しています。あなたは頭のコピーを渡しています。したがって、関数内の頭はNULLです。これでif条件で変更します。ヘッドのローカルコピーは変更されましたが、メインのヘッドはまだ同じです。そのために、実際に挿入は行われていません。 –

+0

'struct node * head'はポインタです。ではない? – learner

0

関数に渡される変数の値を変更したい場合は、参照渡しまたは変数のポインタを使用する必要があります。ここでも同じです。関数insertは、変数headの値をポインタに変更します。したがって、ポインタのポインタを渡す必要があります。

したがって、引数はstruct node **headであり、main()関数のパスは&head~insert()である必要があります。

関連する問題