C语言:head插入新节点程序无法运行,以下情况如何解决
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
void insert(int x)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = head;//涵盖head = NULL情况
head = temp;
}
void print(){
struct Node* temp = head;
printf("list is:");
while (temp != NULL)
{
printf(" %d",temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
head = NULL;
printf("how many numbers?");
int n,i,x;
scanf("%d",&n);
for ( i = 0; i < n; i++)
{
printf("enter the number:\n");
scanf("%d",&x);
insert(x);
print();
}
}