1. 程式人生 > >用單鏈表進行求平均數(去掉最大數,最小數)

用單鏈表進行求平均數(去掉最大數,最小數)

package DataStructureTestmain;


import DataStructureTestSinglyLinkedList.Node;
import DataStructureTestSinglyLinkedList.SinglyLinkedList;


public class SinglyLinkedList_average {
	public static Integer[] random(int n)//返回產生n個隨機數的陣列
	{
		Integer[] element = new Integer[n];
		for(int j=0;j<n;j++)
			element[j]= new Integer((int) (Math.random()*100));
		return element;
	}
	
	public static double averageExceptMaxMin(SinglyLinkedList<Integer> list)
	{
		if(list.isEmpty())
			throw new IllegalArgumentException("不能對空單鏈表計算平均值。");
		
		int sum=0,i=0,max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;//i為資料記錄器
		Node<Integer> p= list.head.next;
		while(p!=null)
		{
			int value= p.data.intValue();
			sum+=value;
			if(value>max)
				max=value;
			if(value<min)
				min=value;
			p=p.next;
			i++;
		}
		
		
		if(i==1|i==2)
			return (double)(sum/i);
		return (double)(sum-max-min)/(i-2);
	}
	
	public static void main(String[] args)
	{
		SinglyLinkedList<Integer> list= new SinglyLinkedList<Integer>(random(10));
		System.out.println("這些數字是"+list.toString());
		System.out.print("去極端平均數"+averageExceptMaxMin(list));
	}
	
}