2017-03-29 31 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()