问题描述
1 - n 个人围坐一圈,约定编号为k的人开始报数,数到m的那个人出列,直到所有人出列,由此产生一个队编号的序列
问题分析
- 先构造一个环形的单向链表
1.首先创建一个Boy类存放next和val
2.创建一个first指针指向第一个节点
3.创建boy指针指向当前新创建的节点
4.创建curBoy指针用来连接新节点 - 出链表
1.判断开始孩子的编号n与总共孩子的个数
2.用一个helper指针用来在删除节点的同时将链表重新环状
code
package com.lemon.josephu;
public class Josephu {
private Boy boy = null;
private Boy first = null;
private Boy curBoy = null;
//添加数据
public void add(int num) {
if(num < 1) {
System.out.println("输入有误,添加失败℃");
return ;
}
for(int i = 1; i <= num; i++) {
boy = new Boy(i);
if(i == 1) {
first = boy;
first.setNext(first);
curBoy = first;
}
else {
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;
}
}
return ;
}
//显示数据
public void show() {
if(first == null) {
System.out.println("环形链表中没有数据℃");
return ;
}
System.out.println("孩子编号:" + first.getVal());
Boy temp = first;
while(temp.getNext() != first) {
temp = temp.getNext();
System.out.println("孩子编号:" + temp.getVal());
}
return ;
}
//依次输出
public void countBoy(int n, int m, int sum) {
if(sum < n) {
System.out.println("输入有误~");
return ;
}
if(first.getNext() == first) {
System.out.printf("孩子的编号:%d\n", first.getVal());
return ;
}
Boy helper = first;
while(helper.getNext() != first) {
helper = helper.getNext();
}
for(int i = 1; i < n; i++) {
first = first.getNext();
helper = helper.getNext();
}
while(first != first.getNext()) {
for(int j = 1; j < m; j++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("孩子的编号:%d\n", first.getVal());
first = first.getNext();
helper.setNext(first);
}
System.out.printf("孩子的编号:%d\n", first.getVal());
return ;
}
}
//Boy类
class Boy {
private int val;
private Boy next;
public Boy(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}```
```java
package com.lemon.josephu;
public class Test {
public static void main(String[] args) {
Josephu josephu = new Josephu();
josephu.add(5);
josephu.show();
josephu.countBoy(2, 3, 5);
}
}