Java带密码的约瑟夫问题

学习作业记录

问题描述:

带密码的约瑟夫问题:编号为1,2,…,n的n个人按照顺时针方向围坐一圈,每个人有自己的编号(正整数)、姓名和密码(正整数)三个数据项。一开始任选一个正整数作为报数上限值,从第一个人开始顺时针方向自1开始报数,报到m时停止报数。报m 的人出列,将他的密码作为新的m值,从他在顺时针方向的下一个人开始重新报数,如此下去,直到所有人全部出队为止。设计一个程序来求出出队顺序。

输入格式:

输入人数 n,再逐行输入每个人的信息(各项之间用逗号隔开),然后输入报数上限值m。

输出格式:

按出队顺序逐行输出每个人的信息,每人信息一行,数据项之间用逗号隔开

输入样例:

在这里给出一组输入。例如:
5
1,刘三,3
2,李丽,5
3,吴勇,8
4,钱多,2
5,齐民,4
2

输出样例:

在这里给出相应的输出。例如:
2,李丽,5
3,吴勇,8
5,齐民,4
4,钱多,2
1,刘三,3
根据bilibili尚硅谷Java数据结构的教学视频完成

代码:

import java.util.Scanner;

public class Main3 {

    public static void main(String[] args) {

        Circle circle=new Circle();
        circle.addNode();
        circle.showPerson();
    }


}
class Circle{
    private Node first=null;
    Scanner sc=new Scanner(System .in);
    int n =sc.nextInt();

    public  void addNode() {
        if(n<1){
            return;
        }
        Node current =null;
        for(int i=1;i<=n;i++){
            String temp=sc.next();
            String [] s=temp.split(",");
            int num = Integer.parseInt(s[0]);
            String nm = s[1];
            int c =Integer.parseInt(s[2]);

            Node person = new Node(num,nm,c);
            if(i==1){
                first=person;
                first.next=first;
                current=first;
            }else{
                current.next=person;
                person.next =first;
                current=person;
            }

        }


    }
    public void showPerson(){
        int m=sc.nextInt();

        if(first==null){
            return;
        }
        Node helper =first;
        while(true){
            if(helper.next==first){
                break;
            }
            helper=helper.next;
        }
        int count=0;
        while(true){

            for(int j=0;j<m-1;j++){
                first=first.next;
                helper=helper.next;
            }

            count++;

            System.out.println(first.number +","+first.name+","+first.code );
            if(n==1){
                break;
            }

            m=first.code;
            if(m>(n-count))
                m=m%(n-count);
            if(m==0){
                m=(n-count);
            }
            first=first.next;
            helper.next=first;
            if(helper==first){
                System.out.print(first.number +","+first.name+","+first.code );
                break;
            }
        }

    }
}
class Node{
    int number;
    int code;
    String name;
    Node next;

    public Node(int number ,String name ,int code){
        this.name =name;
        this.number =number;
        this.code =code;
        this.next=null;
    }
}

J77
发布了7 篇原创文章 · 获赞 2 · 访问量 101

猜你喜欢

转载自blog.csdn.net/weixin_46053704/article/details/105251004