约瑟夫问题
public class Josephus {
public static void main(String[] args){
SingleCircleLinkedList single = new SingleCircleLinkedList();
single.addBoyNode(5);
single.showNodes();
single.countNode(1, 2, 5);
}
}
class SingleCircleLinkedList{
// 创建first节点
private BoyNode first = null;
public void addBoyNode(int nums){
if(nums < 1){
System.out.println("nums的值不正确");
return;
}
BoyNode temp = null; // 辅助节点
for(int i=1;i<=nums;i++){
BoyNode bn = new BoyNode(i);
if(i == 1){
first = bn;
first.setNext(first);
temp = first;
}else{
temp.setNext(bn);
bn.setNext(first);
temp = bn;
}
}
}
// 遍历当前环形链表
public void showNodes(){
if(null == first){
return;
}
BoyNode temp = first;
do{
System.out.println(temp.getNo());
temp = temp.getNext();
}while(first != temp);
}
/**
* startNo:从哪个位置开始数
* countNum 数几次
* nums:一共几个人
*/
public void countNode(int startNo, int countNum, int nums){
if(null == first || startNo<1 || startNo>nums){
System.out.println("参数输入有误,请重新输入");
return;
}
BoyNode helper = first;//辅助节点
while(true){
if(helper.getNext() == first){
break;
}
helper = helper.getNext();
}
for(int j=0; j<startNo-1;j++){
first = first.getNext();
helper = helper.getNext();
}
// 同时移动first,helper m-1次
while(true){
// 圈中只有一个人
if(first == helper){
break;
}
for(int j=0;j<countNum-1;j++){
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩%d出圈!",first.getNo());
// 让first指向的小孩节点出圈
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后的小孩%d出圈!",first.getNo());
}
}
class BoyNode{
private int no;
private BoyNode next;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public BoyNode getNext() {
return next;
}
public void setNext(BoyNode next) {
this.next = next;
}
public BoyNode(int no){
this.no = no;
}
}