รายการที่เชื่อมโยงใช้การจัดสรรหน่วยความจำแบบไดนามิก กล่าวคือ ขยายและย่อขนาดตามลำดับ เป็นชุดของโหนด
โหนดมีสองส่วนดังต่อไปนี้ −
- ข้อมูล
- ลิงค์
ประเภทของรายการที่เชื่อมโยง
ประเภทของลิงค์ลิสต์ในภาษาซีมีดังนี้ −
- รายการเดี่ยว / รายการเดี่ยว
- รายการที่เชื่อมโยงแบบคู่ / แบบทวีคูณ
- รายการเชื่อมโยงแบบวงกลม
- รายการเชื่อมโยงแบบวงกลม
อัลกอริทึม
อ้างอิงอัลกอริธึมที่ให้ไว้ด้านล่างสำหรับการจัดเก็บข้อมูลรถยนต์โดยใช้รายการเชื่อมโยงแบบไดนามิก
ขั้นตอนที่ 1 - ประกาศตัวแปรโครงสร้าง
ขั้นตอนที่ 2 - ประกาศคำจำกัดความของฟังก์ชันที่จะแสดง
ขั้นตอนที่ 3 - จัดสรรการจัดสรรหน่วยความจำแบบไดนามิกให้กับตัวแปร
ขั้นตอนที่ 4 - ใช้ do while loop เพื่อป้อนข้อมูลรถ
ขั้นตอนที่ 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("\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