#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#include< stdbool.h >
typedef struct pnode{
int date;
struct pnode *pnext;
}pnode,linklist;
void creat_list( linklist *L) //新建带头节点链表
{
L = (pnode*)malloc(sizeof(pnode));
if (L)
{
(L)->pnext = NULL;
}
else
{
printf("内存不足以分配malloc");
}
}
bool initlist(linklist *L)//头插法链表初始化
{
int x;
scanf_s("%d", &x);
pnode* newnode=0;
pnode* tailnode = L;
if (!L)
{
return false;
}
if (x != 999)
{
while (x != 999)
{
newnode = (pnode*)malloc(sizeof(pnode));
if (newnode)
{
newnode->date = x;
newnode->pnext = NULL;
tailnode->pnext = newnode;
tailnode = newnode;
printf("请输入数据\n");
scanf_s("%d", &x);
}
else {
printf("空间不足以为newnode分配malloc");
}
}
}
printf("链表初始化完毕\n");
return true;
}
void Printf(struct linklist* L)//打印链表
{
pnode* n;
n = L;
while (n->pnext)
{
n = n->pnext;
printf("%d->", n->date);
}
}
int main()
{
linklist* s;
creat_list(&s);
initlist(&s);
Printf(&s);
return 0;
}
修改如下,供参考:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#include< stdbool.h >
typedef struct pnode{
int date;
struct pnode *pnext;
}pnode,linklist;
void creat_list( linklist *L) //新建带头节点链表
{
L = (pnode*)malloc(sizeof(pnode));
if (L)
{
(L)->pnext = NULL;
}
else
{
printf("内存不足以分配malloc");
}
}
bool initlist(linklist *L)//头插法链表初始化
{
int x;
scanf_s("%d", &x);
pnode* newnode=0;
pnode* tailnode = L;
if (!L)
{
return false;
}
//if (x != 999)
//{
while (x != 999)
{
newnode = (pnode*)malloc(sizeof(pnode));
if (newnode)
{
newnode->date = x;
newnode->pnext = NULL;
tailnode->pnext = newnode;
tailnode = newnode;
printf("请输入数据\n");
scanf_s("%d", &x);
}
else {
printf("空间不足以为newnode分配malloc");
}
}
//}
printf("链表初始化完毕\n");
return true;
}
void Printf(linklist* L)//void Printf(struct linklist* L)//打印链表
{
pnode* n;
n = L;
while (n->pnext)
{
n = n->pnext;
printf("%d->", n->date);
}
printf("\n");
}
int main()
{
linklist* s;
creat_list(s); //&s
initlist(s); //&s
Printf(s); //&s
return 0;
}
我觉得应该是先输出 然后再指向下一个吧 而且有点好奇你这个代码是怎么运行的....
void Printf(struct linklist* L)//打印链表
{
pnode* n;
n = L;
while (n->pnext)
{
printf("%d->", n->date);
n = n->pnext;
}
}
不应该用&传址吗