编写含递归算法的程序实现下面的问题:
a、求单链表中的最大整数
b、求单链表中结点个数
c、求所有证书的平均值
已知head为无头结点单链表的头指针,假设链表中存储的都是整型数据
答案:1 悬赏:10 手机版
解决时间 2021-07-16 21:01
- 提问者网友:像風在裏
- 2021-07-16 01:15
最佳答案
- 五星知识达人网友:笑迎怀羞
- 2021-07-16 01:37
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct _list {
int val;
struct _list* next;
} *node, list;
node Insert( node* head, node pos, int val )
{
node tmp;
tmp = ( node )malloc( sizeof( list ) );
tmp->val = val;
tmp->next = pos ? pos->next : *head;
if ( pos ) {
pos->next = tmp;
} else {
*head = tmp;
}
return tmp;
}
node Create( int* beg, int* end )
{
node head, t;
head = t = NULL;
while ( beg != end ) {
t = Insert( &head, t, *beg++ );
}
return head;
}
void Print( node head )
{
while ( head ) {
printf( "%d ", head->val );
head = head->next;
}
putchar( '\n' );
}
void _max( node head, int* max )
{
if ( head ) {
if ( head->val > *max )
*max = head->val;
_max( head->next, max );
}
}
int Max( node head )
{
int max = head->val;
_max( head, &max );
return max;
}
int Count( node head )
{
return head ? 1 + Count( head->next ) : 0;
}
void _sum( node head, double* avg )
{
if ( head ) {
*avg += head->val;
_sum( head->next, avg );
}
}
double Avg( node head )
{
double sum = 0;
_sum( head, &sum );
return sum / Count( head );
}
int main( void )
{
int a[] = { 3,9,2,7,6,1,8,5,0,4 };
node head = Create( a, a + 10 );
Print( head );
printf( "max: %d\n", Max( head ) );
printf( "count: %d\n", Count( head ) );
printf( "avg: %.2f\n", Avg( head ) );
getch();
return 0;
}
运行截图:
#include <stdlib.h>
#include <conio.h>
typedef struct _list {
int val;
struct _list* next;
} *node, list;
node Insert( node* head, node pos, int val )
{
node tmp;
tmp = ( node )malloc( sizeof( list ) );
tmp->val = val;
tmp->next = pos ? pos->next : *head;
if ( pos ) {
pos->next = tmp;
} else {
*head = tmp;
}
return tmp;
}
node Create( int* beg, int* end )
{
node head, t;
head = t = NULL;
while ( beg != end ) {
t = Insert( &head, t, *beg++ );
}
return head;
}
void Print( node head )
{
while ( head ) {
printf( "%d ", head->val );
head = head->next;
}
putchar( '\n' );
}
void _max( node head, int* max )
{
if ( head ) {
if ( head->val > *max )
*max = head->val;
_max( head->next, max );
}
}
int Max( node head )
{
int max = head->val;
_max( head, &max );
return max;
}
int Count( node head )
{
return head ? 1 + Count( head->next ) : 0;
}
void _sum( node head, double* avg )
{
if ( head ) {
*avg += head->val;
_sum( head->next, avg );
}
}
double Avg( node head )
{
double sum = 0;
_sum( head, &sum );
return sum / Count( head );
}
int main( void )
{
int a[] = { 3,9,2,7,6,1,8,5,0,4 };
node head = Create( a, a + 10 );
Print( head );
printf( "max: %d\n", Max( head ) );
printf( "count: %d\n", Count( head ) );
printf( "avg: %.2f\n", Avg( head ) );
getch();
return 0;
}
运行截图:
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯