少不读水浒 2022-09-24 19:14 采纳率: 57.1%
浏览 66
已结题

输入后,打印出乱码,而且使用f11运行不了,在printf("%d",q->data)

#include<stdio.h>
#include<malloc.h>

img

img

typedef int elemtype;
typedef struct LNode {
elemtype data;
struct LNode* next;

} LNode;

void Initlist(LNode* a)
{
a = (LNode*)malloc(sizeof(LNode));
a->next = NULL;

};

void Headinsert(LNode* a, int n)
{
a = (LNode*)malloc(sizeof(LNode));
a->next = NULL;
for (int i = n; i > 0; i--)
{
LNode* p = (LNode*)malloc(sizeof(LNode));
scanf_s("%d", &(p->data));

    p->next = a->next;
    a->next = p;

};

};
void printlinklist(LNode* a)
{

LNode* q = a;
while (q!=NULL)
{
    
    printf("%d", q->data);
    q = q->next;
};

};

int main(void)

{
LNode L;
Initlist(&L);

Headinsert(&L, 3);

printlinklist(&L);

};

  • 写回答

3条回答 默认 最新

  • qzjhjxj 2022-09-24 19:49
    关注

    修改如下,供参考:

    #include <stdio.h>
    #include <stdlib.h>
    typedef int elemtype;
    typedef struct _LNode {
        elemtype data;
        struct _LNode* next;
    }LNode;
    
    void Initlist(LNode* a)
    {
        //a = (LNode*)malloc(sizeof(LNode));修改
        a->next = NULL;
    }//;
    
    void Headinsert(LNode* a, int n)
    {
        //a = (LNode*)malloc(sizeof(LNode));修改
        a->next = NULL;
        for (int i = n; i > 0; i--)
        {
            LNode* p = (LNode*)malloc(sizeof(LNode));
            scanf("%d", &(p->data));
    
            p->next = a->next;
            a->next = p;
        }//;
    }//;
    void printlinklist(LNode* a)
    {
        LNode* q = a->next; //LNode* q = a;修改
        while (q!=NULL)
        {
            printf("%d ", q->data);
            q = q->next;
        }//;
    }//;
    
    int main(void)
    
    {
        LNode L; //定义了链表的头结点
        Initlist(&L);
        Headinsert(&L, 3);
        printlinklist(&L);
    
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 10月3日
  • 已采纳回答 9月25日
  • 创建了问题 9月24日