
链接列表使用动态内存分配,即它们相应地增长和收缩。它是节点的集合。
节点有两部分,如下所示 -
链表的类型
C 语言中链表的类型如下 -
算法
参考下面给出的算法,使用动态链表存储汽车信息。
步骤 1 - 声明结构变量。
步骤 2 - 声明要显示的函数定义.
第3步 - 为变量分配动态内存。
第4步 - 使用do while循环输入汽车信息。
第5步 - 调用显示函数转到步骤2。
示例
以下是使用动态链表存储汽车信息的C程序 -
Live Demo
#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 %s %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;
}
输出
当上述程序被执行时,它产生以下输出 −
请您注册登录超级码客,加载全部码客文章内容... |