package com.数据结构;import java.util.Scanner;publicclass 环形链表_约瑟夫环 {//有n个人围成一圈,顺序从1开始排号。从第m个人开始报数(从1到3报数),凡报到k的人退出圈子.// 问最后留下的是原来第几号的那位。要求用循环链表实现。//环形链表 (约瑟夫环) ----- 其实没学数据结构之前我就用环形链表做出来了,hahahhahpublicstaticvoidmain(String[] args){
Scanner sc =newScanner(System.in);int n = sc.nextInt();
YouXi youXi =newYouXi(n,1,3);
youXi.sheng();
youXi.out();}}classYouXi{publicint n ;publicint m ;publicint k ;public Boy is ;//初始化后指向第一个位置public Boy ok ;//初始化后指向最后一个位置publicYouXi(int n,int m,int k){//一共n个小朋友 从第m个人开始 报到k出圈this.n = n;this.m = m;this.k = k;}publicvoidsheng(){//生成环形链表for(int i=1;i<=n;i++){//生成n个小孩if(i==1){
is =newBoy(i);
ok = is ;
is.next = is ;}else{
ok.next =newBoy(i);
ok = ok .next ;
ok.next = is ;}}for(int i=0;i<m-1;i++){//将两个指针移到指定位置
is = is.next;
ok = ok.next;}}publicvoidout(){while(is!=ok){for(int i=0;i<k-1;i++){
is = is.next;
ok = ok.next;}// System.out.println(is);
is = is.next;
ok.next = is;}
System.out.println(is);}publicvoidprintf(){//打印链表情况if(is==null)return;
Boy temp = is ;for(int i=0;i<n;i++){
System.out.println(temp);
temp = temp.next ;}}}classBoy{//小孩publicint id ;//编号public Boy next ;publicBoy(int id){this.id = id;}@Overridepublic String toString(){return String.valueOf(this.id);}}