Java解决小孩围圈问题

问题描述:一堆小孩围成一个圈,从第一个小孩开始数,每数到第三个便把第三个孩子删去,数到只剩一个小孩为止,并求该孩子的具体编号。

解决办法

1.

package test;
public class Compare {
    public static void main(String[] args) {
    boolean[] array=new boolean[500];
    for(int i=0;i<array.length;i++) {
        array[i]=true;
    }
    int leftcount = 500;
    int countnum = 0;
    int index = 0;
    
    while(leftcount > 1) {
        if(array[index]) {
         countnum ++;
            if(countnum == 3) {
            countnum = 0;
            array[index] = false;
            leftcount--;
            }
        }
        index ++;
        if(index == 500) {
            index = 0;
        }    
    }
     for(int i=0;i<array.length;i++) {
        if(array[i]) {
        System.out.println(i);
        }
     }
     }
    
}

2.

package test;

public class Studentcircle {
  public static void main(String[] args) {
      makecircle b=new makecircle(500);
      int countnum=0;
      student m=b.first;
      while(b.count>1) {
         countnum++;
         if(countnum==3) {
             countnum=0;
             b.delete(m);
         }
         m=m.right;
      }
      System.out.println(b.first.id);
  }
  
}
class student{
   int id;
   student left;
   student right;
}
class makecircle{
    int count=0;
    student first,last;
    makecircle(int n){
     for(int i=0;i<n;i++) {
        add();
     }
    }
    void add() {
      student x= new student();
      x.id=count;
      if(count<=0) {
         first=x;
         last=x;
         x.left=x;
         x.right=x;
      }else {
         last.right=x;
         x.left=last;
         x.right=first;
         first.left=x;
         last=x;
       }
      count++;
    }
    void delete(student x) {
        if(count<=0) {
        return;
        }else if(count==1) {
            first=last=null;
         }else {
            x.left.right=x.right;
            x.right.left=x.left;
       
          if(x==first) {
             first=x.right;  
          }else if(x==last) {
              last=x.left;
          }
         } 
        count --;
    }
    
}

原文地址:https://www.cnblogs.com/frankzone/p/8098395.html