BJFU_数据结构习题_252递归求解单链表中的结点个数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43722827/article/details/102755486

252递归求解单链表中的结点个数

描述
利用单链表表示一个整数序列,利用递归的方法计算单链表中结点的个数。
输入
多组数据,每组数据有两行,第一行为链表的长度n,第二行为链表的n个元素(元素之间用空格分隔)。当n=0时输入结束。
输出
对于每组数据分别输出一行,对应链表中的各个结点个数。
输入样例 1
4
1 2 3 4
6
1 2 43 5 7 2
0
输出样例 1
4
6

#include<iostream>
using namespace std;
typedef struct LNode
{
    int data;
    struct LNode *next;
}LNode,*LinkList;
void InitList_L(LinkList &L)		
{
    L=new LNode;
    L->next=NULL;
}
void Input_L(LinkList &L,int n)
{
  	LinkList H=L;
	while(n--)
	{
		LinkList p=new LNode;         	
		cin>>p->data;
		p->next=NULL;
		L->next=p;
		L=p;
	}
  	L=H;                    
}
int Length_L(LinkList L)		
{
	if(L->next==NULL)
		return 0; 
    int count=0;
  	count=1+Length_L(L->next);   
	return count;                             
}
int main()
{
	int n;
	while(cin>>n&&n!=0)
    {
      	LinkList L;
		InitList_L(L);
		Input_L(L,n);					
		cout<<Length_L(L)<<endl;		
	}
	return 0;                
}

猜你喜欢

转载自blog.csdn.net/weixin_43722827/article/details/102755486