丢手帕问题

主要通过递归的方式获取最后一个出列的元素

public static String getLastOne(List newList,int commond,int p){
        if(newList.size()==1)
            return newList.get(0);
        int j=newList.size();//当前队列的元素总数
        newList.remove((commond+p-1)%j);//p为当前从第几个元素开始数
        p=(commond+p-1)%j;//记录当前开始接着丢的元素位置
        return getLastOne(newList,commond,p);
 }

以下是main方法

public static void main(String[] args) {
        List<String> mans=new ArrayList<String>();
        mans.add("a");
        mans.add("b");
        mans.add("c");
        mans.add("d");
        mans.add("e");
        mans.add("f");
        mans.add("g");
        mans.add("h");
        mans.add("i");
        mans.add("j");
        mans.add("k");
        mans.add("l");
        mans.add("m");
        mans.add("n");
        mans.add("o");
        mans.add("p");
        int commond=3;
        int position=3;
        System.out.println(getLastOne(mans,commond,position));
    }

猜你喜欢

转载自fairykid.iteye.com/blog/2293774
今日推荐