Josephu问题;
设编号为1,2,… n 的n 个人围坐一圈,约定编号为k(1<=k<=n)的人从1 开始报数,数到m 的那个人出列,它的下一位又从1 开始报数,数到m 的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。
package com.yhc.linkedlist;
public class Josephu {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.add(500);
circleSingleLinkedList.show();
circleSingleLinkedList.outList(11,22,500);
}
}
class CircleSingleLinkedList{
private Boy firstBoy = null;
public void add(int num){
if(num < 1){
System.out.println("请输入大于 1 的数字:");
return;
}
Boy cur = null;
for (int i = 1; i <= num ; i++) {
Boy boy = new Boy(i);
//如果是第一个,先构成一个环状
if(i == 1){
firstBoy = boy;
firstBoy.setNext(boy);
cur = firstBoy;
}else {
cur.setNext(boy);
boy.setNext(firstBoy);
cur = boy;
}
}
}
public void show(){
if(firstBoy == null){
System.out.println("链表为空!");
return;
}
Boy cur = firstBoy;
while(true){
System.out.println("Boy编号:"+cur.getNo());
if(cur.getNext() == firstBoy){
//遍历结束
break;
}
cur = cur.getNext();//向后移动
}
}
//出圈顺序
public void outList(int startNo,int countNo,int num){
//先对数据进行检验
if(firstBoy == null || startNo < 1 || countNo < 1 || num <1){
System.out.println("输入的参数有误!");
return;
}
//first 前面,在删除Boy时使用
Boy preBoy = firstBoy;
while(true){
if (preBoy.getNext() == firstBoy){
break;
}
preBoy = preBoy.getNext();
}
//设置起点位置
for (int i = 0; i < startNo - 1; i++) {
preBoy = preBoy.getNext();
firstBoy = firstBoy.getNext();
}
// 开始移动,被选择(firstBoy)的出圈,圈内剩一个的时候结束
while (true){
if (preBoy == firstBoy){
break;
}
//移动了几次,此时first所指的出圈的
for (int i = 0; i < countNo - 1; i++) {
preBoy = preBoy.getNext();
firstBoy = firstBoy.getNext();
}
System.out.println("Boy :" + firstBoy.getNo() + " out!");
firstBoy = firstBoy.getNext();
preBoy.setNext(firstBoy);
}
System.out.println("最后的Boy是 : " + firstBoy.getNo());
}
}
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;
}
}