노드가 있는 순환 연결 목록이 제공되며 순환 연결 목록에 있는 노드 수를 계산하는 작업입니다.
순환 연결 목록은 첫 번째 요소가 마지막 요소를 가리키고 마지막 요소가 첫 번째 요소를 가리키는 연결 목록의 변형입니다. 단일 연결 목록과 이중 연결 목록은 모두 순환 연결 목록으로 만들 수 있습니다.
아래 프로그램에서는 단일 연결 목록을 순환 연결 목록으로 구현하여 그 안의 노드 수를 계산합니다.

예
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() 함수를 만듭니다.
-
마지막 노드에 첫 번째 노드의 주소를 저장하여 단일 연결 목록이 순환 연결 목록으로 작동하도록 합니다.
-
순환 연결 목록에 있는 총 노드 수를 계산하는 count 함수를 만듭니다.
예시
#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