【头歌】【educoder】【java】链表的中位数

题目描述

补充函数 fun

line 链表是一个有序链表,现请你找出此链表的中位数, 如果链表节点数是偶数,则取中间 2 节点的平均数,保留 2 位小数。

输入格式

本题只需关注 fun 函数,现解释函数参数意义: line: 一个有序链表,有空数据的头结点。

输出格式

本题只需关注 fun 函数,现解释函数返回值意义: 返回中位数,浮点数类型。

输入输出样例

输入1

1 2 3 4 5

输出1

3.00

输入2

1 2 3 4

输出2

2.50

说明/提示

你能通过一次遍历解决此问题吗?

【Java代码及解题思路】

注意:从官方提供的代码中可以看出,测试用例与实际读取的数据不匹配,显然测试用例中在链表输入之前,还存在额外的输入,即链表的长度n1;(代码部分只关注fun()函数即可)

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static class Node {
        public int value;
        public Node next;
    }

    public static Node creat(int[] nums) {
        int cnt = nums.length;
        Node head = new Node();
        Node front_p = head, current_p;

        for (int i = 0; i < cnt; i++) {
            current_p = new Node();
            current_p.value = nums[i];
            front_p.next = current_p;
            front_p = current_p;
        }

        front_p.next = null;
        return head;
    }

    public static void show(Node p) {
        p = p.next;
        while (p != null) {
            System.out.print(p.value + " ");
            p = p.next;
        }
        System.out.println();
    }

    public static double fun(Node line) {
        //start
        List<Integer> list = new ArrayList<>(); // 定义数组存放value
        Node n = line.next;
        while (n != null){
            list.add(n.value);  // 遍历链表,将value加入list
            n = n.next;
        }
        int size = list.size(); // list长度,也是链表长度
        double result = 0;  // 结果
        if(size%2==1){
            result = list.get(((size+1)/2)-1);  // 奇数个
        }else {
            result = (list.get((size/2)-1)+list.get(size/2))/2.0; // 偶数个
        }
        return result;
        //end
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n1 = in.nextInt();
        int a1[] = new int[n1];

        for (int i = 0; i < n1; i++)
            a1[i] = in.nextInt();

        Node line = creat(a1);

        System.out.printf("%.2f\n", fun(line));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值