C program to store the car information using dynamic linked list.

CServer Side ProgrammingProgramming

Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. It is collection of nodes.

Node has two parts which are as follows −

  • Data
  • Link

Types of Linked Lists

The types of linked lists in C programming language are as follows −

  • Single / Singly linked lists
  • Double / Doubly linked lists
  • Circular single linked list
  • Circular double linked list

Algorithm

Refer an algorithm given below for storing the car information by using the dynamic linked list.

Step 1 − Declare structure variables.

Step 2 − Declare Function definition to display.

Step 3 − Allocate dynamic memory allocation to variable.

Step 4 − Use do while loop to enter the car information.

Step 5 − Call display function goto step 2.

Example

Following is the C program for storing the car information by using the dynamic linked list −

 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 \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("enter car color: ");
      scanf("%s",temp->color);
      printf("enter car year: ");
      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;
}

Output

When the above program is executed, it produces the following output −

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
raja
Published on 26-Mar-2021 07:56:46
Advertisements