问题描述:
传送门
哈哈,拥有智慧的人总是能笑到最后。一起向他学习吧。
大致描述就是41个人,从第一个开始报数,谁报到3就原地爆炸,下一个继续从1开始数,如此往复。
解:
约瑟夫环可以看作一个单向循环列表,从头节点开始,把第三个节点删除,并将下一个节点作为头节点,如此往复,就可打印出爆炸顺序。
上代码
public class JosephCircle {
//定义
static class Node{
int data;
Node nextNode;
}
//初始化约瑟夫环:这边写死41,超逼真还原,哈哈。也可以作为将环长作为参数传进来。
static Node initJsephCircle(){
Node head = new Node();
int i = 1;
Node tempNode = new Node();
while(i <= 41){
Node currntNode = new Node();
//记录第一个头节点
if (i == 1){
tempNode = currntNode;
}
currntNode.data = i++;
head.nextNode = currntNode;
head = currntNode;
}
//尾指向头
head.nextNode = tempNode;
return tempNode;
}
public static void main(String[] args){
Node head = initJsephCircle();
int count = 1;
while (head.nextNode != null)
{
//由于是单向链表,故数到2时就爆掉下一个3,并将下下个节点作为头节点。
if(count == 2) {
System.out.println(head.nextNode.data);
head.nextNode = head.nextNode.nextNode;
count = 1;
head = head.nextNode;
continue;
}
count++;
head = head.nextNode;
}
}
}