c语言单链表插入,只输入一个就停止运行了

c语言单链表只输入一个数字就停止运行了

#include
#include
#include
typedef struct node
{
int data;
struct node* next;
}node,linklist;
void initlist(node
L)
{
L->next=NULL;
}
void createlist(node* head,int n)
{
node* s;
node* tail;
int j;
tail=head;
for(int i=0;i
{
scanf("%d",&j);
s=(node*)malloc(sizeof(node));
s->data=j;
tail->next=s;
tail=s;
}
}
void printlist(node* L)
{
while(L->next!=NULL)
{
printf("%d ",L->next->data);
L=L->next;
}
}
void enterlist(node* L,int x,int e)
{
node*p,s;
int i=0;
if(x<=0)
{
printf("-1");
}
p=L;
while(p!=NULL&&i
{
p=p->next;
i++;
}
if(p==NULL)
{
printf("-1");
}
s=(node
)malloc(sizeof(node));
s->data=e;
s->next=p->next;
p->next=s;
}
int main()
{
linklist L;
int n,x,e;
scanf("%d",&n);
initlist(L);
createlist(L,n);
scanf("%d%d",&x,&e);
enterlist(L,x,e);
printlist(L);
return 0;
}

弄了好久,希望实现单链表的插入

修改如下,供参考:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Node
{
    int data;
    struct Node* next;
}node,*linklist;
void initlist(node** L) //修改
{
    (*L) = (node*)malloc(sizeof(node)); //修改
    if ((*L) == NULL)  return;        //修改
    (*L)->next = NULL;                //修改
}
void createlist(node* head,int n)
{
    node* s;
    node* tail;
    int j;
    tail=head;
    for(int i=0;i<n;i++)
    {
        scanf("%d",&j);
        s=(node*)malloc(sizeof(node));
        s->next = NULL;  //修改
        s->data=j;
        tail->next=s;
        tail=s;
    }
}
void printlist(node* L)
{
    while(L->next!=NULL)
    {
        printf("%d ",L->next->data);
        L=L->next;
    }
}
void enterlist(node* L,int x,int e)
{
    node*p,*s;
    int i=0;
    if(x<=0)
    {
        printf("-1\n");
        return;  // 修改
    }
    p=L;
    while(p!=NULL && i < x-1)
    {
        p=p->next;
        i++;
    }
    if(p->next == NULL)//修改
    {
        printf("-1\n");
        return;  // 修改
    }
    s=(node*)malloc(sizeof(node));
    s->data=e;
    s->next=p->next;
    p->next=s;
}
int main()
{
    linklist L;
    int n,x,e;
    initlist(&L); //修改

    scanf("%d",&n);
    createlist(L,n);

    scanf("%d%d",&x,&e);
    enterlist(L,x,e);

    printlist(L);
    return 0;
}

createlist中的L没有分配内存。initlist中只是给L赋值为NULL了。

linklist L;
这个L指针没有分配空间啊