链接列表使用动态内存分配,即它们相应地增长和收缩。它们被定义为节点的集合。这里,节点有两部分,即数据和链路。数据、链接和链表的表示如下 -

链表有四种类型,如下: -
我们使用递归方法求链表长度的逻辑是 -
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("</p><p>enter 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("</p><p>Memory is full");
}
printf("</p><p>press 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
以上就是C程序以找到链表的长度的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号