指针,简单链表输入输出,编译器

求解这个简单的链表,为什么会出错,而且运行过后编译器不能调试了求解
图片说明

 #include<stdio.h>
#include<stdlib.h>
struct node
{
    int date;
    node *next;
};

int main()
{
    int n;
    scanf("%d",&n);
    node *head,*q,*tail;
    node p;
    q = &p;
    int a;
    head = NULL;
    for(int i = 0;i<n;i++)
    {
        scanf("%d",&a);
        q->date = a;
        if(head==NULL)
        {
            head = q;
        }
        else
        {
            tail = q;
        }
        q = q->next;
        q = (node*)malloc(sizeof(node));
    }
    free(q);
    tail->next=NULL;
    node *t = head;
    while(t->next!=NULL)
    {
        printf("%d\n",t->date);
        t = t->next;
    }
    return 0;
}

首先定义的时候应该是struct node *q;以此类推
然后你都没申请p的空间你就拿q指向
其次在你赋值给链表节点的时候,p=p-》next恐怕不对,因为你下面语句申请的空间在堆上,你先让q指向NULL又让它指向堆是神马意思……

我感觉你可以用一个中间变量来跑,比如用tmp=q-》next然后让q=temp这样赋值好一些

不好意思,我刚想了一下,有些地方说错了,你在用之前要先申请内存,把节点赋值,然后再把链挂上,根据你的思想的话,可以这样,tail-》next=q然后再让tail=q就好了,这样就完美了!你的思路其实还挺好的,如果我要写的话可能就用我刚说的别的指针当作tail了