リンクリストに挿入しようとしています。ここで私は同じのために書いたものです:リンク先リストの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の要素を取得しています。
私はここで何が欠けていますか?
頭に割り当てたnew_nodeを添付しませんか? – bruceg
'insert()'は 'main()'から 'head'を変更することはできません。値によって渡されるからです。 – Dmitri
[Cリンクされたリストの重複する可能性がありますなぜ私のリストの先頭の変数がnull(Cの新機能)のままです](http:// stackoverflow。 com/questions/20108412/c-linked-list-why-is-my-list-head-variable-remaining-null-new-to-c) –