日期:2014-05-20 浏览次数:21163 次
import java.util.*; public class betrayer { public static void main(String args[]) { LinkedList<Integer> betrayers = new LinkedList<Integer>(); int number,cnt; for(number = 1;number <=13;number++) betrayers.addLast(number); cnt = 13; number = 0; Iterator it = betrayers.iterator(); while(cnt>1) { if(it.hasNext()) { it.next(); number++; } else { it = betrayers.iterator(); } if(number ==3) { number = 0; it.remove(); cnt--; } } System.out.println("叛徒为:"+betrayers.element()); } }
------解决方案--------------------
import java.util.*; public class Test { public static void main(String[] args) throws Throwable { List<Integer> list = new LinkedList<Integer>(); for (int i=0; i<13; i++) {list.add(i+1);} //13个人放到链表里 int index = 0, num = 0; while (list.size() > 1) { //如果人数大于1 num++; //数数 if (num%3 == 0) { //如果数到3 list.remove(index); 从链表删除 num = 0; //重新数数 } else { //没数到3 index++; //位置前移 } if (index==list.size()) { //如果位置移到最后 //System.out.printf("num: %d, remain: %s\n", num, list); //可以打印查看每轮谁out了 index = 0; //位置重新回到开头 } } System.out.println(list.get(0)); //打印最后一个 } }