BJFU 251递归求解单链表中的最大值

递归求解单链表中的最大值(很简便的方法!nice)

#include <iostream>
using namespace std;

//定义结点
typedef struct Lnode{
	int data;
	struct Lnode *next;
}Lnode,*Linklist; 

//初始化
void Initlist(Linklist &L){
	L=new Lnode;
	L->next=NULL;
} 

//尾插建表(带头结点)
void Creatlist(Linklist &L,int e){
	Lnode *p=new Lnode;
	p->data=e;
	p->next=NULL;
	
	Lnode *cur=L;
	while(cur->next){
		cur=cur->next;
	}
	cur->next=p;
	p->next=NULL;
}

int Findmax(Linklist &L){
  if(L->next==NULL) 
   return L->data; //终止条件(只有头结点)
   
   int max=L->next->data; //设 第一个结点 最大
   
   if(max>Findmax(L->next)) //正式递归
         return max;
   else
    return Findmax(L->next);

}

int main(){
	int n;
	while(cin>>n&&n!=0){
		Linklist L;
		Initlist(L);//初始化 
		for(int i=0;i<n;i++){ //建表  
			 int e; cin>>e;
			 Creatlist(L,e);
		}
		cout<<Findmax(L)<<endl;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值