logcmj 2023-05-25 11:01 采纳率: 40%
浏览 42

代码编译错误是什么原因呢


#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int data;
    struct node* next;
}Lnode,*List;
List Init(List L)
{
    L=(List)malloc(sizeof(Lnode));
    if(L==NULL)
    {
        printf("结点生成失败!");
    }
    L->next=NULL;
    return L;
}
List createList(int len)//尾插法
{
    int i;
    int e;
    List L=Init(L);
    List r,n;
    r=L;//尾指针初始化为头指针
    for(i=0;i<len;i++)
    {
        scanf("%d",&e);
        n=(List)malloc(sizeof(List));//申请空间
        if(n==NULL)
            return NULL;
        n->data=e;
        n->next=NULL;//新指针指针域置空
        r->next=n;//将新指针链入单链表末尾
        r=r->next;//尾指针往后移

    }
    return L;
}
/*List createList(int len)//头插法
{
    int i;
    List L=Init(L);
    List p;
    for(i=0;i<len;i++)
    {
        p=(List)malloc(sizeof(List));
        scanf("%d",&p->data);
        p->next=L->next;//将新结点接入头结点后
        L->next=p;
    }
    return L;
}*/
void printLinkList(List L,int len)
{
    int i;
    if(!L)
        printf("没有元素");
    for(i=0;i<len;i++)
    {
        L=L->next;
        printf("%d ",L->data);
    }
}

int main()
{
    Lnode* L=NULL;
    int len;
    scanf("%d",&len);
    L=createList(len);
    printf("当前链表所有元素");
    printLinkList(L,len);
    return 0;
}
  • 写回答

5条回答 默认 最新

  • diligentForLife 2023-05-25 11:10
    关注

    代码中,有两个地方出现了问题:

    1. 在函数List createList(int len)中,您在申请节点空间时,使用了sizeof(List),这会导致分配的空间大小不正确。List是指向struct node的指针类型,应该使用sizeof(struct node)

    修改前:

    n=(List)malloc(sizeof(List));
    

    修改后:

    n=(List)malloc(sizeof(struct node));
    
    1. 在函数void printLinkList(List L,int len)中,当打印链表元素时,您在循环中使用了L = L->next,这将导致链表的头节点被跳过,从而导致打印结果错误。应该在循环之前将L指向链表的第一个节点。

    修改前:

    for(i=0;i<len;i++)
    {
        L = L->next;
        printf("%d ",L->data);
    }
    

    修改后:

    L = L->next;  // 将L指向链表的第一个节点
    for(i=0;i<len;i++)
    {
        printf("%d ",L->data);
        L = L->next;
    }
    

    通过这些修改,应该能够编译通过并正常运行。

    评论

报告相同问题?

问题事件

  • 创建了问题 5月25日