C语言链表

来源:百度知道 编辑:UC知道 时间:2024/07/05 19:43:44
我都是按书上打的,怎么不会输入和输出?!要怎么输入数据
#include "stdio.h"
#include "stdlib.h"
#define NULL 0
#define LEN sizeof(struct person)
struct person
{
int age;
struct person *next;
};
int n;
struct person *creat()
{
struct person *head;
struct person *p1,*p2;
n=0;
p1=p2=(struct person *)malloc(LEN);
scanf("%d",&p1->age);
head=NULL;
while(p1->age!=0);
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct person *)malloc(LEN);
scanf("%d",&p1->age);
}
p1->next=NULL;
return(head);
}
void print(head)
struct person *head;
{
struct person *p;
printf("\n");
puts("Ages of people:");
p=head;
if(p!=NULL)
do
{
printf("%d ",p->age);
p=p->n

好少看过这样烂的代码

我修改了一下:
#include <stdio.h>
#include <stdlib.h>
#define NULL 0
#define LEN sizeof(struct person)
struct person
{
int age;
struct person *next;
};
int n;
struct person *creat()
{
struct person *head = NULL;
struct person *p1 = NULL;
struct person *p2 = NULL;
n = 0;
while(1)
{
p1 = (struct person *)malloc(LEN);
if(p1 == NULL)
{
break;
}
p1->age = 0;
p1->next = NULL;
scanf("%d",&(p1->age));
if(p1->age == 0)
{
delete p1;
break;
}
n++;
if(1 == n)
{
head = p1;
p2 = p1;
}
else
{
p2->next = p1;
p2 = p1;
}
}
return head;
}
void print(struct person *head)
{
struct person *p;
printf("\n");
puts