c语言动态链表编程问题求解

img

img

请问各位老哥 这下面代码哪里出错了 真的看不出来了(凋谢)


#include<stdio.h>
#include<malloc.h>
struct linknode
{
    int a;
    struct linknode *next;
};
struct linknode *creatnode()
{
    struct linknode *head;
    head=(struct linknode *)malloc(sizeof(struct linknode));
    head=NULL;
    return head;
}
void insertfirst(struct linknode *head)
{
    struct linknode *p1,*p2,*node;
    int num;
    scanf("%d",&num);
    node=(struct linknode*)malloc(sizeof(struct linknode));
    node->a=num;
    node->next=NULL;
    if(head==NULL)
    {
        head=node;
    }
    else
    {
        p1=head;
        head=node;
        node->next=p1;
    }
}
void insertlast(struct linknode *head)
{
    struct linknode *p1,*p2,*node;
    int num;
    scanf("%d",&num);
    node=(struct linknode*)malloc(sizeof(struct linknode));
    node->a=num;
    node->next=NULL;
    p1=head;
    while(p1->next!=NULL)
    {
        p2=p1;
        p1=p2->next;
    }
    p1->next=node;
}
void displink(struct linknode *head)
{
    struct linknode *p;
    p=head;
    while(p!=NULL)
    {
        printf("%d",p->a);
        p=p->next;
    }
}
void freelink(struct linknode *head)
{
    while(head!=NULL)
    {
        free(head);
    }
    head=head->next;
}
int main()
{
    int n;
    scanf("%d",&n);
    struct linknode *head;
    head=creatnode();
    int i;
    for(i=1;i<=n;i++)
    {
        if(i%2!=0)
        {
            insertfirst(head);
        }
        else
        {
            insertlast(head);
        }
    }
    displink(head);
    freelink(head);
    return 0;
}

13行改成head->next = NULL啊。malloc刚分配了head空间,你接着就把head设置为空啊?
69行也很奇怪啊,head不是空,你就free掉head,那head还是不为空啊,你这就死循环了

struct linknode *node;
while(head!= NULL)
{
    node = head->next;
    free(head);
    head = node;
}