思路:把h调到尾结点,返回h->date,将返回的值赋给max,然后max和当前的h->date比较,max大将max返回,max小则max=h->date,返回max
递归方程
h->next==0 return h->date
h->next!=0 max=MaxValue(h->next)
if(h->date>max)
max=h->date;
return maxl
运行环境:VS2017
代码实现
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int date;
struct node*next;
}ElemSN;
//创建链表
ElemSN*GreatLink(int Date[], int n)
{
int i;
ElemSN*p, *t = 0, *h = 0;
for (i = 0;i < n;i++)
{
p = (ElemSN*)malloc(sizeof(ElemSN));
p->date = Date[i];
p->next = NULL;
if (!h)
h = t = p;
else
t = t->next = p;
}
return h;
}
//输出链表
PrintLink(ElemSN*h)
{
ElemSN*p;
for (p = h;p;p = p->next)
printf("%3d", p->date);
printf("\n");
}
int MaxValue(ElemSN*h)
{
int max = 0;
if (!h->next)
{
return h->date;
}
else
{
max = MaxValue(h->next);
if (h->date > max)
max = h->date;
return max;
}
}
int main(void)
{
int a[8] = { 3,2,5,8,4,7,6,9 };
int i = 0;
ElemSN*head;
head = GreatLink(a, 8);
PrintLink(head);
i = MaxValue(head);
printf("%d\n", i);
system("pause");
}
运行结果
3 2 5 8 4 7 6 9
9
请按任意键继续. . .
本文介绍了如何使用C语言通过递归方式在数据域值不重复的非空单向链表中找到最大值。首先将链表尾部节点的值设为最大值,然后比较当前节点值与最大值,根据比较结果更新最大值,并继续遍历。最后返回最大值。
&spm=1001.2101.3001.5002&articleId=102825046&d=1&t=3&u=e5a225049ef744639ec3d82b75ce7f0c)
734

被折叠的 条评论
为什么被折叠?



