C++循环链表节点计数
给定一个包含节点的循环链表,任务是计算循环链表中存在的节点数。
循环链表是链表的一种变体,其中第一个元素指向最后一个元素,最后一个元素指向第一个元素。单链表和双链表都可以转换为循环链表。
在下面的程序中,我们将单链表实现为循环链表,以计算其中的节点数。

例如
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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP