用链表解决约瑟夫问题
约瑟夫问题其实就是自己构建一个循环链表就可以解决了
public class YLinkedList {
public static void main(String[] args) {
//总人数m
int m = 6;
MyNode head = new MyNode(1);
head.next = head;
MyNode cur = head;
for (int i = 2; i <= m ; i++) {
MyNode temp = new MyNode(i);
cur.next = temp;
cur = cur.next;
}
cur.next = head;
//数到5踢出去
int n = 5;
while (cur.next != cur){//当只剩最后一个数的时候跳出循环
for (int i = 1; i < n; i++) {
cur = cur.next;
}
System.out.println(cur.next.value);
cur.next = cur.next.next;//找到报5数字的那个节点,断开它的指针,就是让该节点的前一个节点的next指向该节点的后一个节点。
}
System.out.println("幸运者是:"+cur.value);
}
}
class MyNode {//定义一个节点
int value;
MyNode next;
public MyNode(int value) {
this.value = value;
this.next = null;
}
}