代码如下:
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);
}
}
本文链接:https://my.lmcjl.com/post/17199.html
4 评论