单链表 Segmentation fault (core dumped)

好像是while 那里的判断null失败了,代码不知道错哪里了

img

img

15行 L->next=NULL
21,22行 p->next=L->next; L->next=p; L是链首无变化,变的是L->next,每次被新的p覆盖,加入第二个新节点就有问题了。可以这样改:
p->next=L; L=p; 每次新增节点,新节点下一个指向L,然后让L指向新节点,新节点放链首。如果新节点放链尾,每次增加节点需要循环到链尾去,像print()里面那样循环。

最主要的问题在源代码第14行:L = (LNode *)malloc(sizeof(LNode)); 这行多余了,删除即可。

img

img

修改如下,供参考对照:

#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
#define Status int
typedef struct LNode{
    ElemType data;
    struct LNode* next;
}LNode;
Status init(LNode * L)
{
    L->next = NULL;
    return 1;
}
Status insert(LNode *L, ElemType a)
{
    LNode *p = (LNode *)malloc(sizeof(LNode));
    p->data = a;
    p->next = L->next;
    L->next = p;
    return 0;
}
void print(LNode * L)
{
    LNode *p = L->next;
    while (p){
        printf("%c,", p->data);
        p = p->next;
    }
}
int main()
{
    LNode L;
    init(&L);
    for (int i = 0; i < 10; i++)
         insert(&L, 'a' + i);
    print(&L);

    return 0;
}