Java 编写 约瑟夫环(Joseph Ring)游戏

import java.util.Scanner;
public class TestJosephRing {
 public static void main(String[] args) {
Scanner input = new Scanner(System.in);
 System.out.print("输入组成约瑟夫环的孩子数目(大于1的整数):");
 int sum = input.nextInt();
 System.out.print("输入约瑟夫环游戏的循环数(大于1的整数):");
 int cyc = input.nextInt();
 kidCircle kc = new kidCircle();
 for(int i = 0;i<sum;i++){
  kc.add();
  }
kid k =new kid();
k=kc.first;
for(int i=0;i<sum;i++){System.out.print(k.id+" ");k=k.right;}
System.out.println();
//System.out.println(kc.count);
 int index = kc.josephRing(cyc);
 if(index == -1){System.out.println("围成约瑟夫环的孩子数量不够(数量应当多于一个)");}
 else if(index != -1){System.out.println("约瑟夫环游戏留到最后的孩子的ID号是   "+index);}
 else System.exit(-1);
 }
}

class kid{
 int id;
 kid right;
 kid left;


}

class kidCircle {
 int count  = 0;
 kid first;
 kid last;

void add(){
  kid k = new kid();
  
 if(count == 0){
  k.id = 0;
  first = k;
  last = k;
  k.right = k;
  k.left = k;
 }
 else { k.id = count;
  last.right = k;
  k.left = last;
  first.left  = k;
  k.right = first;
  last = k; 
 }
 count++;
 }

void del(kid k) {
 if(count == 0){System.out.println("围成约瑟夫环的孩子数量不够(数量应当多于一个)");}
 if(count == 1){first = null;last = null;}
 if(count > 1){
 k.left.right = k.right;
 k.right.left = k.left; 
 if(first == k){
  last.right = first.right;
  first.right.left = last;
  first = first.right;
  }
 if(last == k){
  last.left.right = first; 
  first.left = last.left;
  last = last.left;
}
}
}
int josephRing(int cyc){
 int num;
 kid k=first;
 if(count <= 1){
 return -1;
 }
 while(count>1){
  for(num=1;num<cyc;num++){
  k=k.right;
  }
  if(num == cyc){
   del(k);


kid v =new kid();
v=first;
for(int i=0;i<count-1;i++){System.out.print(v.id+" ");v=v.right;}
System.out.println();

k=k.right;
   }
  num = 1;
  count--; 
 }
 return first.id;
}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值