package linkedlist;
public class Josephe {
public static void main(String[] args) {
CircleSingleList circleSingleList = new CircleSingleList();
// circleSingleList.add(5);
// circleSingleList.show();
circleSingleList.solution(5,1,2);
}
}
class CircleSingleList{
CircleNode first = null;//定义一个指针指向单向循环列表的头结点
// 向单向循环列表里添加num个节点
public void add(int num) {
if (num < 1){
System.out.println("输入的参数有误");
}
CircleNode curr = null;//记录当前节点的位置
for (int i = 1; i <= num; i++) {
CircleNode newCircleNode = new CircleNode(i);
if (i == 1){
first = newCircleNode;
curr = first;
}else {
curr.setNext(newCircleNode);
curr = curr.getNext();
}
}
curr.setNext(first);//最后一个节点指向第一个节点
}
// 显示循环链表中的元素,从头结点开始打印
public void show(){
if (first == null) {
System.out.println("链表为空");
return;
}
// 当前位置的指针
CircleNode curr = first;
while (curr.getNext() != first){
System.out.println(curr);
curr = curr.getNext();
}
System.out.println(curr);
}
// 解决约瑟夫问题的方法
public void solution(int n,int k, int m){//定义n个节点个数,第k个为起始位置,喊m下
if (n < 1 || k < 1 || m < 1 || k > n){
System.out.println("参数错误");
return;
}
add(n);//生成一个n个环形链表
CircleNode helpNode = first;
//让helpNode 指向first前一个节点
while (helpNode.getNext() != first){
helpNode = helpNode.getNext();
}
for (int i = 0; i < k-1; i++) {
helpNode = helpNode.getNext();
first = first.getNext();//将first移动到第K个位置
}
while (true){
if (first == helpNode){
break;
}
// 找到要出去节点的前一个节点
CircleNode curr = helpNode;
for (int i = 0; i < m-1; i++) {
curr = curr.getNext();
}
System.out.println(curr.getNext());
//将改节点删除
curr.setNext(curr.getNext().getNext());
helpNode = curr;
first = helpNode.getNext();
}
System.out.println(first);
}
}
class CircleNode{
private int no;
private CircleNode next;
public CircleNode(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public CircleNode getNext() {
return next;
}
public void setNext(CircleNode next) {
this.next = next;
}
@Override
public String toString() {
return "CircleNode{" +
"no=" + no +
'}';
}
}