我試圖插入到我的鏈接列表中。以下是我寫的一樣:頭在鏈接列表中始終爲空插入
#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));
到主功能,我正在第一元件作爲零和其他插入。
我在這裏錯過了什麼?
你不想附加你分配給head的new_node嗎? – bruceg
'insert()'不能從'main()'修改'head',因爲它是按值傳遞的。你需要傳遞一個指向它的指針(即指向指向結構節點的指針) – Dmitri
[C鏈接列表爲什麼我的列表頭變量保持爲空(新到C)](http:// stackoverflow。 com/questions/20108412/c-linked-list-why-is-my-list-head-variable-remaining-null-new-to-c) –