使用動態連結串列儲存汽車資訊的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

更新於:2021年3月26日

3K+ 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始學習
廣告