Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C จัดเก็บข้อมูลรถยนต์ด้วย Dynamic Linked List

Linked List ใช้การจัดสรรหน่วยความจำแบบไดนามิก ขยาย/หดได้ เป็นการรวบรวมโหนด (nodes)

โหนดมี 2 ส่วน:

  • Data (ข้อมูล)
  • Link (ลิงก์ไปโหนดถัดไป)

ประเภท Linked Lists

  • Singly linked list
  • Doubly linked list
  • Circular singly linked list
  • Circular doubly linked list

อัลกอริทึม

ขั้นตอน 1 - ประกาศตัวแปรโครงสร้าง (struct)

ขั้นตอน 2 - ประกาศฟังก์ชัน display

ขั้นตอน 3 - จัดสรรหน่วยความจำไดนามิก

ขั้นตอน 4 - ใช้ do-while loop รับข้อมูลรถยนต์

ขั้นตอน 5 - เรียกฟังก์ชัน display

ตัวอย่าง

โปรแกรม C จัดเก็บข้อมูลรถยนต์ด้วย Dynamic Linked List:

#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; }

ผลลัพธ์

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