C程序以找到链表的长度

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

C程序以找到链表的长度

链表的类型

链表有四种类型,如下: –

单链表/ 单链表双/双向链表循环单链表循环双链表

我们使用递归方法求链表长度的逻辑是 –

int length(node *temp){   if(temp==NULL)      return l;   else{      l=l+1;      length(temp->next);   }}

登录后复制

程序

以下是求链表长度的C程序 –

 现场演示

#include #include 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 lengthint length(node *temp){   if(temp==NULL)      return l;   else{      l=l+1;      length(temp->next);   }}

登录后复制

输出

当执行上述程序时,会产生以下结果 –

Run 1:enter the elements in a list: 3press 1 to enter data into list: 1enter the elements in a list: 56press 1 to enter data into list: 1enter the elements in a list: 56press 1 to enter data into list: 0The list has 3 no of nodesRun 2:enter the elements in a list: 12press 1 to enter data into list: 1enter the elements in a list: 45press 1 to enter data into list: 0The list has 2 no of nodes

登录后复制

以上就是C程序以找到链表的长度的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2583088.html

(0)
上一篇 2025年3月6日 14:29:00
下一篇 2025年2月27日 18:59:32

AD推荐 黄金广告位招租... 更多推荐

发表回复

登录后才能评论