java 实现约瑟夫环的实例代码

时间:2021-05-19

复制代码 代码如下:
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Josephus {
private static class Node{
int No;
Node next;
public Node(int No){
this.No=No;
}
}
public static void main(String[] args) {
int totalNum,cycleNum;
List<Integer> list = new ArrayList<Integer>();
Scanner cin = new Scanner(new BufferedInputStream(System.in));
System.out.println("请输入总人数:");
totalNum=cin.nextInt();
System.out.println("请输入报数人数:");
cycleNum=cin.nextInt();
Node header = new Node(1);
Node pointer = header;
for(int i=2;i<=totalNum;i++){
pointer.next = new Node(i);
pointer = pointer.next;
}
pointer.next= header;
pointer=header;
while(pointer != pointer.next){
int i =2;
while(i<cycleNum){
pointer = pointer.next;
i++;
}
//list.add(pointer.next.No);
System.out.println("将序号"+pointer.next.No+"剔除。");
pointer.next=pointer.next.next;
pointer=pointer.next;
}
System.out.println("这是最后一个人:"+pointer.No);
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章