单向链表的建立程序异常退出


#include<stdio.h>//无头节点 
#include<stdlib.h>
typedef struct List
{
    int val;
    struct List *next;
}list;
int main()
{
    list *head,*last,*p;
    head=(list*)malloc(sizeof(struct List));
    head=NULL;head->next=NULL;//这个地方删除head->=NULL后可以建立长度大于一的链表、不删去则程序结束
    int i,n;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        p=(list*)malloc(sizeof(struct List));
        scanf("%d",&(p->val));
        if(head==NULL)
        {
            head=p;
            last=head;
        }
        else
        {
            last->next=p;
            last=p;
            last->next=NULL; 
        }
    }
    while(head)
    {
        printf("%d ",head->val);
        head=head->next;
    }
}

问题1,为什么这一行删去后当输入1时会是死循环
问题2,为什么不删去时程序异常结束

head=(list*)malloc(sizeof(struct List));
这里分配了内存
然后下面
head = NULL;
这又是干嘛

供参考:

#include<stdio.h>//无头节点
#include<stdlib.h>
typedef struct List
{
    int val;
    struct List *next;
}list;
int main()
{
    list *head,*last,*p;
    //head=(list*)malloc(sizeof(struct List));  这行多余,删除    修改
    head=NULL; //head->next=NULL; 这里也删除  //这个地方删除head->=NULL后可以建立长度大于一的链表、不删去则程序结束
    int i,n;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        p=(list*)malloc(sizeof(struct List));
        scanf("%d",&(p->val));
        if(head==NULL)
        {
            head=p;
            last=head;
        }
        else
        {
            last->next=p;
            last=p;
            //last->next=NULL; 这行不能只放在这里  修改
        }
        last->next=NULL; // 移动到这里             修改
    }
    while(head)
    {
        printf("%d ",head->val);
        head=head->next;
    }
    return 0;
}