首頁  >  文章  >  後端開發  >  用動態鍊錶儲存汽車資訊的C程序

用動態鍊錶儲存汽車資訊的C程序

WBOY
WBOY轉載
2023-09-17 18:33:051167瀏覽

用動態鍊錶儲存汽車資訊的C程序

連結清單使用動態記憶體分配,即它們相應地增長和收縮。它是節點的集合。

節點有兩個部分,如下所示-

  • 資料
  • 連結

鍊錶的類型

# 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 \t\t %s \t\t %d",temp->model,temp->color,temp->year);
      temp=temp->next;
      printf("</p><p>");
   }
}
int main(){
   int n;
   char option,enter;
   head=(struct node *)malloc(sizeof(struct node));
   temp=head;
   do{
      printf("</p><p>enter car model: ");
      scanf("%s",temp->model);
      printf("enter car color: ");
      scanf("%s",temp->color);
      printf("enter car year: ");
      scanf("%d",&temp->year);
      printf("</p><p>Do you want continue Y(es) | N(o) : ");
      scanf("%c",&enter);
      scanf("%c",&option);
      if (option!=&#39;N&#39;){
         temp->next=(struct node *)malloc(sizeof(struct node));
         temp=temp->next;
      } else {
         temp->next=NULL;
      }
   }while(option!=&#39;N&#39;);
   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

以上是用動態鍊錶儲存汽車資訊的C程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除