รายการที่เชื่อมโยงใช้การจัดสรรหน่วยความจำแบบไดนามิก กล่าวคือ ขยายและย่อขนาดตามลำดับ พวกมันถูกกำหนดให้เป็นชุดของโหนด ในที่นี้ โหนดมีสองส่วน คือ ข้อมูลและลิงก์ การแสดงข้อมูล ลิงค์ และรายการที่เชื่อมโยงได้รับด้านล่าง -

ประเภทของรายการที่เชื่อมโยง
รายการที่เชื่อมโยงมีสี่ประเภทซึ่งมีดังนี้ -
- รายการเดี่ยว / รายการเดี่ยว
- รายการที่เชื่อมโยงแบบคู่ / แบบทวีคูณ
- รายการเชื่อมโยงแบบวงกลม
- รายการเชื่อมโยงแบบวงกลม
ตรรกะที่เราใช้ในการหาความยาวของรายการที่เชื่อมโยงโดยใช้วิธีการเรียกซ้ำคือ −
int length(node *temp){
if(temp==NULL)
return l;
else{
l=l+1;
length(temp->next);
}
} โปรแกรม
ต่อไปนี้เป็นโปรแกรม C เพื่อค้นหาความยาวของรายการที่เชื่อมโยง -
#include <stdio.h>
#include <stdlib.h>
typedef struct linklist{
int data;
struct linklist *next;
}node;
int l=0;
int main(){
node *head=NULL,*temp,*temp1;
int len,choice,count=0,key;
do{
temp=(node *)malloc(sizeof(node));
if(temp!=NULL){
printf("\nenter the elements in a list : ");
scanf("%d",&temp->data);
temp->next=NULL;
if(head==NULL){
head=temp;
}else{
temp1=head;
while(temp1->next!=NULL){
temp1=temp1->next;
}
temp1->next=temp;
}
}else{
printf("\nMemory is full");
}
printf("\npress 1 to enter data into list: ");
scanf("%d",&choice);
}while(choice==1);
len=length(head);
printf("The list has %d no of nodes",l);
return 0;
}
//recursive function to find length
int length(node *temp){
if(temp==NULL)
return l;
else{
l=l+1;
length(temp->next);
}
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Run 1: enter the elements in a list: 3 press 1 to enter data into list: 1 enter the elements in a list: 56 press 1 to enter data into list: 1 enter the elements in a list: 56 press 1 to enter data into list: 0 The list has 3 no of nodes Run 2: enter the elements in a list: 12 press 1 to enter data into list: 1 enter the elements in a list: 45 press 1 to enter data into list: 0 The list has 2 no of nodes