约瑟夫环的解决
问题描述:有m个人围成一个圈,指定从第n个人开始依次报数,每报到K时的人出列,然后出列后面的人从1继续报数,
无限循环直到剩下一个人为止
** 代码实现(以环形链表方式)
** 节点类
public class Node {
int id;
Node next;
public Node(int id) {
this.id = id;
}
}
** 环形链表类
public class RoundLinkedList {
private Node first;
public void createJosephRound(int count){
if(count<1){
System.out.println("个数需要大于0");
return;
}
Node current=null;
for (int i = 1; i <=count; i++) {
Node node=new Node(i);
if(i==1){
first=node;
first.next=first;
current=first;
}else {
current.next=node;
node.next=first;
current=node;
}
}
}
public void show(){
if(first==null){
System.out.println("没有数据");
return;
}
Node current=first;
while (true){
System.out.println("当前节点id "+current.id);
if(current.next==first){
break;
}
current=current.next;
}
}
public void Joseph(int start,int step,int count){
if(step<1||start<1||start>count||first==null){
System.out.println("数据有误");
return;
}
Node current=first;
while (current.next != first) {
current = current.next;
}
for (int i = 0; i < start-1; i++) {
first=first.next;
current=current.next;
}
while (current != first) {
for (int i = 0; i < step - 1; i++) {
first = first.next;
current = current.next;
}
System.out.println("编号为" + first.id + "出列");
first = first.next;
current.next = first;
}
System.out.println("剩下的节点id为 "+first.id);
}
}
** 测试类
public class RoundLinkedListTest {
public static void main(String[] args) {
RoundLinkedList round=new RoundLinkedList();
round.createJosephRound(5);
round.show();
round.Joseph(1,2,5);
}
}