可以用单项循环链表来解决约瑟夫问题。
代码实现:
ublic class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.show();
circleSingleLinkedList.Josepfu();
}
}
class CircleSingleLinkedList {
private Boy first = new Boy(-1);
public void addBoy(int nums) {
if (nums < 1) {
System.out.println("nums的值不正确");
return;
}
Boy curBoy = first;
for (int i = 1; i <= nums; i++) {
if (i == 1) {
first.setNo(i);
curBoy.setNext(first);
} else {
Boy boy = new Boy(i);
curBoy.setNext(boy);
curBoy = boy;
curBoy.setNext(first);
}
}
}
public void show() {
if (first == null) {
System.out.println("链表为空");
return;
}
//辅助指针
Boy curBoy = first;
while (true) {
System.out.println("编号为" + curBoy.getNo());
if (curBoy.getNext() == first)
break;
curBoy = curBoy.getNext();
}
}
public void Josepfu() {
int m = 1;
int n = 2;
Scanner scanner = new Scanner(System.in);
//System.out.println("请输入开始报数的小孩编号");
//m = scanner.nextInt();
//System.out.println("请输入出列序号");
//n = scanner.nextInt();
Boy curBoy = first;
while (true) {
curBoy = curBoy.getNext();
if(curBoy.getNext() == first) {
break;
}
}
while (true) {
if(curBoy.getNext() == curBoy) {
break;
}
for (int i = 0; i < n - 1; i++) {
curBoy = curBoy.getNext();
}
System.out.println("序号是"+curBoy.getNext().getNo());
curBoy.setNext(curBoy.getNext().getNext());
}
System.out.println("最后一个是"+curBoy.getNo());
}
}
class Boy {
private int no;
private Boy next;
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;
}
public Boy(int no) {
this.no = no;
}
}