完整程序:
#include <stdio.h>
#include <stdlib.h>
//创建结构体
struct lb
{
int x;
struct lb * pnext;
};
struct lb * create_list(void)//建造链表函数
{
int len;//用来存放有效节点的个数
int i;
int val;//用来临时存放用户输入的节点的值
//分配一个不存放有效数据的有节点
struct lb * phead = (struct lb *)malloc(sizeof(struct lb));
if(NULL == phead)
{
printf("分配失败,程序终止\n");
exit(0);
}
struct lb * ptail = phead;
ptail->pnext = NULL;
printf("输入需要生成的节点的个数:len = ");
scanf("%d", &len);
for(i=0; i<len; ++i)
{
printf("亲输入第%d个节点的值:", i+1);
scanf("%d", &val);
struct lb * pnew = (struct lb *)malloc(sizeof(struct lb));
if(NULL == pnew)
{
printf("分配失败,程序终止\n");
exit(0);
}
pnew->x = val;
ptail->pnext = pnew;
pnew->pnext = NULL;
ptail = pnew;
}
return phead;
}
//输出链表
void output_list(struct lb * ph)
{
struct lb * p;//传递值的中间变量
p = ph->pnext;
while(p!=NULL)
{
printf("%d ", p->x);
p = p->pnext;
}
printf("\n");
}
int main(void)
{
struct lb * phead = create_list();
output_list(phead);
return 0;
}