1.什么约瑟夫问题:
- 一群小朋友在一起丢手绢,有n个小朋友
- 选定一个小朋友作为第一个人,开始报数,第一个小朋友数1,当报到第m个数的时候,那么那个人出局,
- 然后他的下一个小朋友再次从1开始报数,再次数到第m个数,再次出局,如此循环,直到剩下1个小朋友
2.我们使用单向循环链表来解决这个问题
3.我们创建一个循环单链表的节点类
class BoyNode{
private int no;
private BoyNode next;
public BoyNode(int no) {
this.no = no;
}
@Override
public String toString() {
return "BoyNode{" +
"no=" + no +
'}';
}
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;
}
}
4. 创建循环单链表的类以及展示
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList list = new CircleSingleLinkedList();
list.addBoy(5);
list.showBoy();
list.countBoy(2,2,5);
}
}
class CircleSingleLinkedList{
private BoyNode first = new BoyNode(-1);
public void addBoy(int nums){
if(nums<1){
System.out.println("nums的值不正确");
return;
}
BoyNode curBoy = null;
for (int i = 1; i <= nums ; i++) {
BoyNode boy = new BoyNode(i);
if (i==1){
first = boy;
curBoy = first;
first.setNext(first);
}else{
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;
}
}
}
public void showBoy(){
if (first == null){
System.out.println("链表为空");
return;
}
BoyNode curBoy = first;
while (true){
System.out.printf("小孩的编号为%d\n",curBoy.getNo());
if (curBoy.getNext()==first){
break;
}
curBoy = curBoy.getNext();
}
}
public void countBoy(int startNo,int countNum,int nums){
if (first==null||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();
}
while (true){
if (helper==first){
break;
}
for (int j = 0 ;j<countNum-1;j++){
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩%d出圈\n",first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后留在圈中的小孩编号%d\n",helper.getNo());
}
}
class BoyNode{
private int no;
private BoyNode next;
public BoyNode(int no) {
this.no = no;
}
@Override
public String toString() {
return "BoyNode{" +
"no=" + no +
'}';
}
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;
}
}