约瑟夫环问题
- 问题描述
设编号为1,2…n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的人出列,依次类推直到所有人出列为止,由此产生一个出队编号序列。 - 问题分析
a.创建一个单向的环形链表,按编号插入节点,显示节点
class Boy{
private int no;
private Boy next;
public Boy(int no){
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}
//单向循环链表
class CircleSingleLinkedlist{
private Boy first =null;
//添加节点
public void addBoy(int n){
if(n<1){
System.out.println("添加的数目错误");
return;
}
Boy curboy = first;
for(int i=1;i<=n;i++){
Boy boy = new Boy(i);
if(i==1){
first = boy;
first.setNext(first);
curboy=boy;
}else {
curboy.setNext(boy);
boy.setNext(first);
curboy = boy;
}
}
}
//显示节点
public void showBoy(){
if(first==null){
System.out.println("链表为空");
return;
}
Boy curBoy = first;
while (true){
if(curBoy.getNext()==first){
System.out.printf("第%d个小孩",curBoy.getNo());
System.out.println();
break;
}else{
System.out.printf("第%d个小孩",curBoy.getNo());
curBoy = curBoy.getNext();
System.out.println();
}
}
}
b. 创建辅助指针helper 指向环形链表的最后一个节点。报数前让first和helper移动到k位置,即移动k-1次。报数开始:first,helper移动m-1次,出圈,重新连接节点:first=first.next; helper.next=first;直到圈中只有一个节点。
public void countBoy(int startNum,int countNum, int totalNum){
if(first==null||startNum>totalNum||startNum<1){
System.out.println("输入有误");
return;
}
//创建helper节点指向环的最后一个节点。
Boy helper = first;
while (true){
if(helper.getNext()==first){
break;
}
helper = helper.getNext();
}
// 将first和helper同时移动startNum-1c次
for(int i=0;i<startNum-1;i++){
first=first.getNext();
helper=helper.getNext();
}
//开始报数 ,即first和helper同时移动countNum-1次,first位置即为要出圈的序号
while (true){
if(first==helper){
break;
}
for(int i =0;i<countNum-1;i++){
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("出队的编号为%d\n",first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.println("留在圈中的编号"+first.getNo());
}