约瑟夫问题简述
一堆人围成一圈,从1开始报数,若报到5则此人出圈,剩下人重新从1开始报数,问最后剩下的人是谁;
解决办法
单向循环链表,放在一个while循环中,在剩下一个人之前(head.next=head),若遇到count==5,则删除这个结点,count重新从1开始计数,当循环结束时,剩下的head就是最后一个人
小细节
在删除循环链表的结点时,必须知道前一个结点,在写循环的时候需要注意保证每个循环体里同时有当前结点和当前结点的前一个结点。
代码实现
package primDataStructure;
public class josephuQuestion {
class cirNode{
private String name;
public cirNode next;
public String getName() {
return name;
}
public void deleteNext(cirNode preNode) {
preNode.next=this.next;
}
public cirNode(String name) {
this.next=this;
this.name=name;
}
}
public void solution() {
cirNode head=new cirNode("同学0");
for(int i=1;i<30;i++) {
cirNode node=new cirNode("同学"+i);
node.next=head.next;
head.next=node;
}
int count=1;
cirNode preNode=head;
while(head.next!=head) {
preNode=head;
head=head.next;
System.out.println(head.getName()+"叫号为"+count);
if(count==5) {
System.out.println(head.getName()+"叫到5,出列");
count=1;
head.deleteNext(preNode);
}
count++;
}
System.out.println("最后剩下了"+head.getName());
}
public static void main(String args[]) {
josephuQuestion question=new josephuQuestion();
question.solution();
}
}