500个人围成一个圈子,数够3人,就退出1个,问最后剩下的是几号?
检验先有5个人,应该留下第4个人,由于是数组,所以第四个人的下标是3.
/*achieve the funtion :count 3 kids, the quit the third kid
use the object thinking */
public class Test{
public static void main(String[] args) {
KidCircle kc = new KidCircle(5);
int countNum = 0;
Kid k = kc.first;
while(kc.count > 1){
countNum ++;
if(countNum ==3){
countNum =0;
kc.delete(k);
}
k = k.right;
}
System.out.println(kc.first.id);
}
}
/* define class Kid*/
class Kid{
int id;
Kid left; //left is means the current kids'left kid
Kid right; //right is means the current kids'right kid
}
/* define class KidCircle*/
class KidCircle{
int count = 0; //mean the circles'number
Kid first,last; //define the circles' first kid and last kid.
KidCircle(int n){//Constructor :new n numbers kid circle
for(int i = 0;i<n;i++){
add();
}
}
/*add a kid in the last kids'right*/
void add(){
/*
first: new a kid;
id = count
*/
Kid k = new Kid();
k.id = count;
/*if no kid in the circle ,the new kid is the first kid and is the last kid
*/
if(count <=0){
first = k;
last = k;
k.left = k;
k.right = k;
}
/*if has some kids in the circle,the new kid will stand at the last kids'right,and the new
kids'left is the last kid. another: the new kids'right is the first kids'lest*/
else{
last.right = k;
k.left = last;
k.right = first;
first.left = k;
last = k;
}
count ++;
}
void delete(Kid k){
if(count <= 0){
return;
}else if(count == 1){
first = last =null;
}else{
k.left.right = k.right;
k.right.left = k.left;
if(k == first){
first = k.right;
}else if(k == last){
last = k.left;
}
}
count --;
}
}