#include
#include
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);
};
修改如下,供参考:
#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;
}
如果你是想动态分配空间,那么首先在main里就定义LNode *L = NULL;然后InitList(&L);
代码修改如下:
void Initlist(LNode** a)
{
(*a) = (LNode*)malloc(sizeof(LNode));
(*a)->next = NULL;
}
void Headinsert(LNode* a, int n)
{
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->next;
while (q!=NULL)
{
printf("%d", q->data);
q = q->next;
}
}
int main(void)
{
LNode *L = NULL;
Initlist(&L);
Headinsert(L, 3);
printlinklist(L);
}
初始化函数里不要动态分配空间了。main里定义的不指针类型变量,已经分配空间了