在单链表里如何将所有的unique data进行average

原题目是:Calculate the average of all unique data in a LLL

题目中的LLL就是linear linked list,翻译成就是单链表。
至于单链表的知识点,小编就不在此介绍了。

下面是代码展示

//This is the list.h
#include<iostream>
#include<cctype>
#include<cstring>

using namespace std;

struct node
{
    int data;
    node * next;
};

class list
{
    public:
        //These funtions are already writter to you
        list();  //supplied
        ~list(); //supplied
        void build(); //supplied
        void display(); //supplied

        //Average all the unique data in the LLL
        float average_unique();

    private:
        //Average all the unique data in the LLL
        float average_unique(node * head, node * current, int & num);
        int average_unique(node * head, int num);
};

解释一下,在.h文件里,在private session,参数num 为什么要return by reference? 因为这个num是专门将所有的unique data求和的结果存储起来的。

下面是展示如何用递归来实现这个功能:

//This is the list.cpp file
#include "list.h"

float list::average_unique()
{
    int num = 0;
    float result = average_unique(head,head,num);
    return float(num / result);
}

float list::average_unique(node * head, node * current, int & num)
{
    if(!head || !current)
        return 0.0;
    if(average_unique(head,current->data) == 1)
    {
        cout<<current->data<<" ";
        num += current->data;
        return average_unique(head,current->next,num) + 1;
    }
    return average_unique(head,current->next,num);
}

int list::average_unique(node * head, int num)
{
    if(!head)
        return 0;
    if(head->data == num)
        return average_unique(head->next,num) + 1;
    return average_unique(head->next,num);
}

如果大家会如何找到unique data,那么这儿将所有的unique data进行average,那应该不是很难,就是添加一点运算。

下面是运行结果展示:

这就是如何实现这个功能的代码。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值