美文网首页
单链表递归求平均数

单链表递归求平均数

作者: KM_0d16 | 来源:发表于2019-09-24 23:27 被阅读0次

    设计一个算法:实现用递归求单链表的平均数

    实现思路

    通过递归循环累加,要注意用double类型,避免在递归过程中用int会被强制转换导致最后误差

    实现代码

    public class LNode {
        LNode next;
        double data;
    
        public LNode(LNode next, int data) {
            this.next = next;
            this.data = data;
        }
    }
    
     /**
         * 求平均值函数
         * @param node 单链表头结点
         * @param n 单链表长度
         * @return 平均值
         */
        public static double average(LNode node, int n) {
            if(node.next == null) {
                return node.data;
            }
            return (average(node.next, n - 1) * (n - 1) + node.data) / n;
        }
    
    

    测试代码

     public static void main(String[] args) {
            LNode L1 = new LNode(null,2);
            LNode L2 = new LNode(L1,3);
            LNode L3 = new LNode(L2,5);
            LNode L4 = new LNode(L3,10);
    
            double result = average(L4, 4);
            System.out.print(result);
        }
    输出结果5.0
    

    相关文章

      网友评论

          本文标题:单链表递归求平均数

          本文链接:https://www.haomeiwen.com/subject/wqabuctx.html