编写一个链表结构关于车的属性,读取任意多辆车的车型、车牌号、外形颜色、价钱输入。之后遍历链表,再将链表数据打印出来。
#include<stdio.h>
#include<stdlib.h>
typedef struct vehicle
{
int number;
char color[8];
char xinghao[80];
int price;
struct vehicle *next;
}car;
int n;
car *create()
{
car *head,*p1,*p2;
n=0;
p1=p2=(car*)malloc(sizeof(car));
printf("请输入车型、车号、颜色、价格\n");
scanf("%s %d %s %d",p1->xinghao,&p1->number,p1->color,&p1->price);
while(p1->number!=0)
{
n++;
if(n==1)
head=p1;
else p2->next=p1;
p2=p1;
p1 = (car*) malloc(sizeof(car));
scanf("%s %d %s %d",p1->xinghao,&p1->number,p1->color,&p1->price);
}
p2->next=NULL;
return (head);
}
int print(car *head)
{
struct vehicle *p;
if(head==NULL)
return;
for(p=head;p!=NULL;p=p->next)
printf("车型为%s 车号为%d 车颜色为%s 车价格为%d\n",p->xinghao,p->number,p->color,p->price);
}
int main()
{
car *car1;
car1=create();
print(car1);
}
输出
输入
宝马320Li 3811 红色 20015
宝马520Li 4311 蓝色 35833
0 0 0 0