Chiken find good fater

阅读更多
/**
 * 
 */
package com.mzl.tms;

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

/**
 * @author mzl
 * 
 */
public class ChikenLookingFatherTest {

	public static void main(String[] args) {

		Chiken kichen_1 = ChikenMother.born("kichen_1");
		Chiken kichen_2 = ChikenMother.born("kichen_2");
		Chiken kichen_3 = ChikenMother.born("kichen_3");// chiken_3 is bad body
		kichen_3.setBadMan(true);
		Chiken kichen_4 = ChikenMother.born("kichen_4");
		//kichen_4.setBadMan(true);
		Chiken kichen_5 = ChikenMother.born("kichen_5");

		kichen_4.setFather(kichen_2);
		kichen_2.setFather(kichen_1);
		kichen_1.setFather(kichen_3);
		kichen_3.setFather(kichen_5);

//		Chiken kichen  =  sort(kichen_4); 
		
		Chiken k = findGoodFather(kichen_4);
		setGoodFather(k);
		
		while (k != null) {
			System.out.println(k.getName());
			k = k.getFather();
		}
		
		
	}
	
	public static Chiken sort(Chiken kichen){
		List list = new ArrayList(5);
		Chiken tmp = kichen;
		
		while(tmp != null){
			if(tmp.isBadMan()){
				tmp = tmp.getFather() ;
			}else{
				Chiken c = tmp.getFather();
				
				tmp.setFather(null);
				list.add(tmp);
				tmp = c; 
			}
		}
		
		int number = list.size();
		if(number == 0){
			return null;
		}else if(number ==1){
			return list.get(0);
		}else if(number == 2){
			list.get(0).setFather(list.get(1));
			return list.get(0);
		}else{
			for(int i = 0 ; i< list.size() - 1 ; i++){
				list.get(i).setFather(list.get(i+1));
			}
			return list.get(0);
		}
	}
	
	/**
	 * 
	 * @param chiKen
	 */
	public static void setGoodFather(Chiken chiKen){
		Chiken father = chiKen.getFather();
		if(father==null){
			return ;
		}
		
		if(father.isBadMan()){
			Chiken tmpFather = findGoodFather(chiKen);
			chiKen.setFather(tmpFather);
			if(tmpFather!=null)
				setGoodFather(tmpFather);
		}else{
			setGoodFather(father);
		}
		
	}
	
	/**
	 * 
	 * @param chiKen
	 * @return
	 */
	public static Chiken findGoodFather(Chiken chiKen){
		if(chiKen.getFather()!=null){
			if(!chiKen.getFather().isBadMan()){
				return chiKen.getFather();
			}else{
				return findGoodFather(chiKen.getFather());
			}
		}
		return null; 
	}
}











你可能感兴趣的:(java)