使用动态链表存储汽车信息的C程序。
链表使用动态内存分配,即它们会根据需要增长和缩小。它是由节点组成的集合。
节点有两个部分,如下所示:
- 数据
- 链接
链表的类型
C编程语言中的链表类型如下:
- 单向链表
- 双向链表
- 循环单向链表
- 循环双向链表
算法
请参考以下算法,该算法使用动态链表存储汽车信息。
步骤1 - 声明结构体变量。
步骤2 - 声明显示函数的定义。
步骤3 - 为变量分配动态内存。
步骤4 - 使用do while循环输入汽车信息。
步骤5 - 调用显示函数,跳转到步骤2。
示例
以下是使用动态链表存储汽车信息的C程序:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char model[10],color[10];
int year;
struct node *next;
};
struct node *temp,*head;
void display(struct node *head){
temp=head;
while(temp!=NULL){
if(temp->year>2010 && (strcmp("yellow",temp->color)==0))
printf(" %s \t\t %s \t\t %d",temp->model,temp->color,temp->year);
temp=temp->next;
printf("
");
}
}
int main(){
int n;
char option,enter;
head=(struct node *)malloc(sizeof(struct node));
temp=head;
do{
printf("
enter car model: ");
scanf("%s",temp->model);
printf("enter car color: ");
scanf("%s",temp->color);
printf("enter car year: ");
scanf("%d",&temp->year);
printf("
Do you want continue Y(es) | N(o) : ");
scanf("%c",&enter);
scanf("%c",&option);
if (option!='N'){
temp->next=(struct node *)malloc(sizeof(struct node));
temp=temp->next;
} else {
temp->next=NULL;
}
}while(option!='N');
display(head);
return 0;
}输出
执行上述程序后,将产生以下输出:
enter car model: I20 enter car color: white enter car year: 2016 Do you want continue Y(es) | N(o) : Y enter car model: verna enter car color: red enter car year: 2018 Do you want continue Y(es) | N(o) : Y enter car model: creta enter car color: Maroon enter car year: 2010 Do you want continue Y(es) | N(o) : N
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP