查找链表长度的 C 语言程序
链表使用动态内存分配,即它们会根据需要进行增长和收缩。它们被定义为一组节点。在此,节点有两个部分,分别是数据和链接。下面给出数据、链接和链表的表示:

链表类型
链表有四种类型,如下所示:
- 单链表
- 双链表
- 循环单链表
- 循环双链表
我们用来通过递归方法查找链表长度的逻辑是:
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("
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("
Memory is full");
}
printf("
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP