首页 > 编程 > Java > 正文

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

2019-11-26 15:57:15
字体:
来源:转载
供稿:网友
复制代码 代码如下:

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);
    }
}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表