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

ตัวอย่าง
Input − nodes-: 20, 1, 2, 3, 4, 5 Output − count of nodes are-: 6 Input − nodes-: 20, 1, 2, 3, 4, 5, 7, 8, 9, 12 Output − count of nodes are-: 10
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
-
สร้างโครงสร้างสำหรับรายการที่เชื่อมโยงอย่างเดียวรวมถึงที่อยู่และข้อมูลที่โหนดเก็บไว้
-
สร้างฟังก์ชัน push() ที่จะใช้เพื่อแทรกข้อมูลลงในโหนด
-
ในโหนดสุดท้าย ให้เก็บที่อยู่ของโหนดแรกเพื่อสร้างฟังก์ชันรายการที่เชื่อมโยงโดยลำพังเป็นรายการที่เชื่อมโยงแบบวงกลม
-
สร้างฟังก์ชันการนับที่จะนับจำนวนโหนดทั้งหมดที่อยู่ในรายการที่เชื่อมโยงแบบวงกลม
ตัวอย่าง
#include <stdio.h>
#include <stdlib.h>
/* Defining a node */
struct node {
int data;
struct node* next;
};
// Inserting node in Circular list
void push(struct node** head_ref, int data){
struct node* ptr1 = (struct node*)malloc(sizeof(struct node));
struct node* temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
// going to the last node to insert new element.
if (*head_ref != NULL){
while (temp->next != *head_ref){
temp = temp->next;
}
temp->next = ptr1;
} else{
ptr1->next = ptr1; //for first node
}
*head_ref = ptr1;
}
// Function to count the number of nodes
int count_fun(struct node* head){
struct node* temp = head;
int result = 0;
if (head != NULL){
do {
temp = temp->next;
result++;
} while (temp != head);
}
return result;
}
int main(){
/* Initializing the list as empty */
struct node* head = NULL;
push(&head, 10);
push(&head, 20);
push(&head, 30);
push(&head, 40);
printf("count of nodes are: %d", count_fun(head));
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
count of nodes are: 4