题目描述
补充函数 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));
}
}