思路都在注释中。
import java.util.*;
public class Joseph {
public int getResult(int n) {
// write code here
LinkedList<Integer> list = new LinkedList<Integer>();
for(int i = 0;i<n;i++){
list.add(i+1);
}
int cur = 0;
int index = 0;
int round = 2;
while(list.size()>1){
index = 0;
//下面这层循环是确定round之后对整个链表的操作
while(list.size()>1&&index<list.size()){
cur = (cur+1)%round;
if(cur!=1){
list.remove(index);
}else{
index++;
}
}
round++;
cur =0;
if(list.size()>1){
//尾部节点移到头部,重新开始操作
int last = list.removeLast();
list.addFirst(last);
}
}
return list.get(0);
}
}