2017-03-29 27 views
-1

我試圖插入到我的鏈接列表中。以下是我寫的一樣:頭在鏈接列表中始終爲空插入

#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: 

爲什麼沒有元素插入列表中?

如果我移動

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

到主功能,我正在第一元件作爲零和其他插入。

我在這裏錯過了什麼?

+0

你不想附加你分配給head的new_node嗎? – bruceg

+0

'insert()'不能從'main()'修改'head',因爲它是按值傳遞的。你需要傳遞一個指向它的指針(即指向指向結構節點的指針) – Dmitri

+0

[C鏈接列表爲什麼我的列表頭變量保持爲空(新到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

所以,你已經將頭部設置爲NULL。你傳遞它來插入函數。你正在傳送一份頭像。所以函數裏面的頭是NULL。現在你在if條件中改變它。頭部的地方副本已經改變,但主要頭部仍然是一樣的。對此,實際上沒有插入。 –

+0

'struct node * head'是一個指針。不是嗎? – learner

0

無論何時您想要更改傳遞給某個函數的某個變量的值,都需要通過引用或使用該變量的指針傳遞。這裏的情況也是如此。功能insert更改變量head的值,這是一個指針。所以你必須傳遞指針的指針。

因此,參數必須是struct node **head,並且在main()函數中傳遞&headinsert()