这一次是借鉴模仿别人写的代码,以前觉得不好将数据结构的链结构什么的迁移到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); } }