亲宝软件园·资讯

展开

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

人气:0
想了解java 实现约瑟夫环的实例代码的相关内容吗,在本文为您仔细讲解java约瑟夫环的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,约瑟夫环,下面大家一起来学习吧。
复制代码 代码如下:

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);
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论