链接列表使用动态内存分配,即它们会相应地增长和收缩。它是节点的集合。
节点分为以下两个部分:
数据
关联
用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("\n");
}
}
int main(){
int n;
char option,enter;
head=(struct node *)malloc(sizeof(struct node));
temp=head;
do{
printf("\nenter car model: ");
scanf("%s",temp->model);
printf("输入汽车颜色: ");
scanf("%s",temp->color);
printf("输入汽车年份: ");
scanf("%d",&temp->year);
printf("\nDo 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 输入汽车颜色: white 输入汽车年份: 2016 Do you want continue Y(es) | N(o) : Y enter car model: verna 输入汽车颜色: red 输入汽车年份: 2018 Do you want continue Y(es) | N(o) : Y enter car model: creta 输入汽车颜色: Maroon 输入汽车年份: 2010 Do you want continue Y(es) | N(o) : N