头插法建立单链表,带头结点。输出不对,实在找不到错误的地方了

#include
#include
struct lnode *creat(int n);

struct lnode {
int data;
struct lnode *next;
};

int main() {
int n;
struct lnode *q;
printf("输入你想创建的节点数:\n");
scanf("%d", &n);
q = creat(n);
while (q) {
printf("%d", q->data);
q = q->next;
}

return 0;

}

struct lnode *creat(int n) {
int i;
struct lnode *p;
int a;
struct lnode *head = (struct lnode *)malloc(sizeof(struct lnode));
head->next = NULL;
for (i = n - 1; i >= 0; i--) {
p = (struct lnode *)malloc(sizeof(struct lnode));
scanf("%d", &a);
p->data = a;
p->next = head->next;
head->next = p;

}
return head;

}

q = creat(n);
while (q) {
printf("%d", q->data);
q = q->next;
}
这样把头节点的值都输出来了

修改如下,供参考:

#include <stdio.h>
#include <malloc.h>
struct lnode* creat(int n);
struct lnode {
    int    data;
    struct lnode* next;
};

int main() {
    int n;
    struct lnode* q, * head;
    printf("输入你想创建的节点数:\n");
    scanf("%d", &n);
    head = q = creat(n);
    while (q->next) {
        printf("%4d", q->next->data);
        q = q->next;
    }
    return 0;
}

struct lnode* creat(int n) {
    int i;
    struct lnode* p;
    int a;
    struct lnode* head = (struct lnode*)malloc(sizeof(struct lnode));
    head->next = NULL;
    for (i = n - 1; i >= 0; i--) {
        p = (struct lnode*)malloc(sizeof(struct lnode));
        scanf("%d", &a);
        p->data = a;
        p->next = head->next;
        head->next = p;
    }
    return head;
}